import { useState, useEffect, useMemo } from 'react';
import { toast } from 'sonner';
import { Bot, Settings, Mail, Volume2, Mic, ScanText, X } from 'lucide-react';
import { useQueryClient } from '@tanstack/react-query';
import type { LayoutNode, PanelComponents } from 'officerdev';
import { WorkspaceLayout, TerminalView } from 'officerdev';
import { usePanelChannel } from 'hooks/usePanelChannel';

import { createSettingsPanelComponents, type SettingsSectionGroup } from './SettingsPanel';
import { RUN_COMMAND_CHANNEL, type RunCommandState } from './ServerSettings/run-command-channel';
import { SMTPSection } from './ServerSettings/SMTPSection';
import { TTSSection } from './ServerSettings/TTSSection';
import { STTSection } from './ServerSettings/STTSection';
import { OCRSection } from './ServerSettings/OCRSection';

const groups: SettingsSectionGroup[] = [
  {
    label: 'AI',
    icon: Bot,
    sections: [
      {
        key: 'tts',
        icon: Volume2,
        title: 'Text to Speech',
        description: 'TTS provider and voice',
        content: <TTSSection />,
      },
      { key: 'stt', icon: Mic, title: 'Speech to Text', description: 'Whisper server URL', content: <STTSection /> },
      {
        key: 'ocr',
        icon: ScanText,
        title: 'OCR',
        description: 'Vision model for text extraction',
        content: <OCRSection />,
      },
    ],
  },
  {
    label: 'Email',
    icon: Mail,
    sections: [
      { key: 'smtp', icon: Mail, title: 'SMTP', description: 'Email delivery provider', content: <SMTPSection /> },
    ],
  },
];

const { Sidebar, Content } = createSettingsPanelComponents({
  globalKey: 'SYSTEM_SETTINGS_SELECTED',
  sidebarIcon: Settings,
  sidebarLabel: 'System',
  groups,
});

const baseLayout: LayoutNode = {
  type: 'group',
  id: 'system-root',
  direction: 'horizontal',
  children: [
    { node: { type: 'panel', id: 'system-left', appType: null }, size: 20 },
    { node: { type: 'panel', id: 'system-right', appType: null }, size: 80 },
  ],
};

const splitLayout: LayoutNode = {
  type: 'group',
  id: 'system-root',
  direction: 'horizontal',
  children: [
    { node: { type: 'panel', id: 'system-left', appType: null }, size: 20 },
    {
      node: {
        type: 'group',
        id: 'system-right-group',
        direction: 'vertical',
        children: [
          { node: { type: 'panel', id: 'system-right', appType: null }, size: 50 },
          { node: { type: 'panel', id: 'system-terminal', appType: null }, size: 50 },
        ],
      },
      size: 80,
    },
  ],
};

const SystemTerminalPanel = () => {
  const queryClient = useQueryClient();
  const [state, setState] = usePanelChannel<RunCommandState>(RUN_COMMAND_CHANNEL, null);
  const [session, setSession] = useState<{ id: string; command: string } | null>(null);

  useEffect(() => {
    if (state && (!session || session.command !== state.command)) {
      setSession({ id: `run-cmd-${Date.now()}`, command: state.command });
    } else if (!state) {
      setSession(null);
    }
  }, [state]);

  const close = () => setState(null);

  const onCommandDone = (exitCode: number, output: string) => {
    if (state) {
      for (const key of state.refetchKeys) {
        queryClient.invalidateQueries({ queryKey: [key] });
      }
    }
    if (exitCode === 0) {
      toast.success('Command completed successfully');
    } else {
      toast.error(output || `Command failed with exit code ${exitCode}`, { duration: 8000 });
    }
    setState(null);
  };

  if (!state || !session) return null;

  return (
    <div className="h-full flex flex-col">
      <div className="shrink-0 px-4 py-1.5 border-b border-duck-dark/10 dark:border-foreground/10 bg-background/60 flex items-center gap-2">
        <span className="text-xs font-medium text-duck-dark/50 dark:text-foreground/50 flex-1">Run Command</span>
        <button
          onClick={close}
          className="p-1 rounded hover:bg-duck-dark/10 dark:hover:bg-foreground/10 cursor-pointer transition-colors"
        >
          <X className="h-3.5 w-3.5 text-duck-dark/50 dark:text-foreground/50" />
        </button>
      </div>
      <TerminalView className="flex-1" command={session.command} sessionId={session.id} onCommandDone={onCommandDone} />
    </div>
  );
};

export const SystemSettings = () => {
  const [runCommand] = usePanelChannel<RunCommandState>(RUN_COMMAND_CHANNEL, null);

  const layout = useMemo(() => (runCommand ? splitLayout : baseLayout), [runCommand]);

  const panelComponents: PanelComponents = useMemo(
    () => ({
      'system-left': Sidebar,
      'system-right': Content,
      'system-terminal': SystemTerminalPanel,
    }),
    [],
  );

  return (
    <div className="h-full w-full pt-2">
      <WorkspaceLayout layout={layout} onLayoutChange={() => {}} components={panelComponents} />
    </div>
  );
};
