import { useMemo } from 'react';
import { Bot, Settings, Mail, Volume2, Mic, ScanText } from 'lucide-react';
import type { LayoutNode, PanelComponents } from 'officerdev';
import { WorkspaceLayout } from 'officerdev';

import { SettingsRoute, createSettingsPanelComponents, type SettingsSectionGroup } from './SettingsPanel';
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 BASE_PATH = '/settings/system';

const { Sidebar, Content, allSections } = createSettingsPanelComponents({
  basePath: BASE_PATH,
  sidebarIcon: Settings,
  sidebarLabel: 'System',
  groups,
});

// There used to be a second layout here that split a terminal in below the settings content, driven by a
// `system-settings:run-command` channel: a section asked for a sudo command, this screen grew a pane, ran
// it, and invalidated the queries the section named. Its only writer was the AI harness installer, and
// that moved server-side to `POST /server-settings/chat-providers/install` — leaving a channel whose two
// remaining writes were both `setState(null)`, a pane nothing could ever open, and a layout nothing could
// ever select. Removed rather than rewired; the install path it existed for no longer wants a terminal.
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 },
  ],
};

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

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