import React, { useState, useEffect } from 'react';
import { SessionList } from '@/components/ai/SessionList';
import { ChatWindow } from '@/components/ai/ChatWindow';
import { ResizablePanel } from '@/components/ui/ResizablePanel';
import { usePluginToolbarStore } from '@/store/pluginToolbarStore';
import { fetchAgents, createSession, type AIAgent } from '@/api/ai';
import { ChevronLeft, Folder, Plus } from 'lucide-react';

export function AIAssistantPage() {
  const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
  const [agents, setAgents] = useState<AIAgent[]>([]);
  const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
  const [mobileView, setMobileView] = useState<'list' | 'chat'>('list');
  const [refreshKey, setRefreshKey] = useState(0);
  const { registerItems, unregisterPlugin } = usePluginToolbarStore();

  useEffect(() => { fetchAgents().then(setAgents).catch(() => {}); }, []);

  useEffect(() => {
    registerItems('ai_assistant', [
      {
        id: 'agent-select',
        plugin: 'ai_assistant',
        label: 'Agent',
        type: 'select',
        group: 'agent',
        selectOptions: agents.map((a) => ({ value: a.id, label: a.name })),
        selectValue: selectedAgentId || '',
        onSelect: (val: string) => setSelectedAgentId(val || null),
        onClick: () => {},
      },
      {
        id: 'new-chat',
        plugin: 'ai_assistant',
        label: 'Neuer Chat',
        type: 'button',
        group: 'actions',
        icon: (
          <Plus className="w-3.5 h-3.5" strokeWidth={2} />
        ),
        onClick: async () => {
          try {
            const session = await createSession({ is_sidebar: false });
            setActiveSessionId(session.id);
            setMobileView('chat');
            setRefreshKey(k => k + 1);
          } catch (e) {
            console.error('Failed to create session:', e);
          }
        },
      },
      {
        id: 'new-folder',
        plugin: 'ai_assistant',
        label: 'Ordner',
        type: 'button',
        group: 'actions',
        icon: (
          <Folder className="w-3.5 h-3.5" strokeWidth={2} />
        ),
        onClick: () => {
          const name = prompt('Ordnername:');
          if (name) {
            import('@/api/ai').then(({ createFolder }) => {
              createFolder({ name }).then(() => setRefreshKey(k => k + 1)).catch(() => {});
            });
          }
        },
      },
    ]);
    return () => unregisterPlugin('ai_assistant');
  }, [agents, selectedAgentId, registerItems, unregisterPlugin]);

  const handleSelectSession = (id: string) => { setActiveSessionId(id); setMobileView('chat'); };

  return (
    <div className="flex h-full" data-testid="ai-assistant-page">
      {/* Desktop: two-pane layout */}
      <div className="hidden md:flex">
        <ResizablePanel
          initialWidth={288}
          minWidth={200}
          maxWidth={500}
          className="border-r border-secondary-200 bg-white"
          data-testid="ai-session-pane"
        >
          <SessionList key={refreshKey} activeSessionId={activeSessionId} onSelectSession={setActiveSessionId} className="h-full" />
        </ResizablePanel>
      </div>
      <div className="hidden md:flex flex-1 flex-col">
        {activeSessionId ? <ChatWindow sessionId={activeSessionId} agentId={selectedAgentId} className="flex-1" /> : (
          <div className="flex-1 flex items-center justify-center text-secondary-400"><div className="text-center"><div className="text-4xl mb-3">🤖</div><div className="text-sm">Wähle einen Chat oder erstelle einen neuen</div></div></div>
        )}
      </div>
      {/* Mobile: single-pane view switching */}
      <div className="flex md:hidden flex-1 flex-col overflow-hidden">
        {mobileView === 'list' && (
          <div className="flex-1 flex flex-col bg-white">
            <SessionList key={refreshKey} activeSessionId={activeSessionId} onSelectSession={handleSelectSession} className="flex-1" />
          </div>
        )}
        {mobileView === 'chat' && activeSessionId && (
          <div className="flex-1 flex flex-col">
            <div className="h-14 flex items-center gap-2 px-3 border-b border-secondary-200 bg-white">
              <button onClick={() => setMobileView('list')} className="p-2 rounded-lg hover:bg-secondary-100" aria-label="Zurück">
                <ChevronLeft className="w-5 h-5" strokeWidth={2} />
              </button>
              <span className="text-sm font-medium text-secondary-700 truncate">Chat</span>
            </div>
            <ChatWindow sessionId={activeSessionId} agentId={selectedAgentId} className="flex-1" />
          </div>
        )}
        {mobileView === 'chat' && !activeSessionId && (
          <div className="flex-1 flex items-center justify-center text-secondary-400"><div className="text-center"><div className="text-4xl mb-3">🤖</div><div className="text-sm">Wähle einen Chat</div></div></div>
        )}
      </div>
    </div>
  );
}
