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 className="ux-page-stack">
      <PageHeader
        title="Settings"
        description="Manage your account, credentials, and runtime configuration from one place."
      />

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

      <div className="ux-surface settings-legacy-surface p-5" style={{ color: 'var(--foreground)' }}>
        {section === 'Account'     && <SettingsTab botState={botState} />}
        {section === 'Bot Config'  && isAdmin && <ConfigTab />}
        {section === 'Admin Panel' && isAdmin && <AdminTab botState={botState} socket={socket} />}
      </div>
    </div>
  );
}
