import { useEffect, useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useAppContext } from '../context/AppContext';
import { SettingsTab } from '../tabs/SettingsTab';
import { AdminTab } from '../tabs/AdminTab';
import { ConfigTab } from '../tabs/ConfigTab';
import { PageHeader } from '../components/ui/page-header';
import { Button } from '../components/ui/Primitives';

type SettingsSection = 'Account' | 'Bot Config' | 'Admin Panel';

export function SettingsView() {
  const { botState, isAdmin, socket } = useAppContext();
  const [searchParams, setSearchParams] = useSearchParams();
  const sections: SettingsSection[] = [
    'Account',
    ...(isAdmin ? ['Bot Config' as SettingsSection] : []),
    ...(isAdmin ? ['Admin Panel' as SettingsSection] : []),
  ];
  const requestedSection = searchParams.get('section');
  const initialSection = useMemo<SettingsSection>(() => {
    if (requestedSection === 'Bot Config' && isAdmin) return 'Bot Config';
    if (requestedSection === 'Admin Panel' && isAdmin) return 'Admin Panel';
    return 'Account';
  }, [requestedSection, isAdmin]);
  const [section, setSection] = useState<SettingsSection>(initialSection);

  useEffect(() => {
    setSection(initialSection);
  }, [initialSection]);

  const handleSectionChange = (nextSection: SettingsSection) => {
    setSection(nextSection);
    setSearchParams(nextSection === 'Account' ? {} : { section: nextSection });
  };

  return (
      <div>
      <PageHeader
        title="Settings"
        description="Manage your account, credentials, and runtime configuration from one place."
      />

      <div className="tab-strip" style={{ marginBottom: 24 }}>
        {sections.map(s => (
          <Button
            key={s}
            type="button"
            onClick={() => handleSectionChange(s)}
            variant="ghost"
            size="sm"
            className="tab-button"
            data-active={section === s}
          >
            {s}
          </Button>
        ))}
      </div>

      <div
        className="settings-legacy-surface"
        style={{
          background: 'var(--card)',
          border: '1px solid var(--border)',
          borderRadius: 24,
          padding: 24,
          boxShadow: 'var(--card-shadow)',
          color: 'var(--foreground)',
        }}
      >
        {section === 'Account'     && <SettingsTab botState={botState} />}
        {section === 'Bot Config'  && isAdmin && <ConfigTab />}
        {section === 'Admin Panel' && isAdmin && <AdminTab botState={botState} socket={socket} />}
      </div>
    </div>
  );
}
