'use client';

import { useEffect, useState } from 'react';
import { usePathname, useRouter } from 'next/navigation';
import { Sidebar } from './components/Sidebar';
import {
  addAgent,
  addQuickAction,
  addConversation,
  addMessage,
  listAgents,
  listConversations,
  listQuickActions,
  seedBuiltinAgents,
  seedBuiltinQuickActions,
  updateAgent,
  updateQuickAction,
} from '../lib/db';
import type { Agent, Conversation, QuickAction } from '../lib/types';
import { migrateV3ToV4 } from '../lib/migrate';
import { CommandPalette } from './components/CommandPalette';
import { QuickActionEditor } from './components/QuickActionEditor';
import { AgentEditor } from './components/AgentEditor';

export default function WorkspaceLayout({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const pathname = usePathname();
  const [collapsed, setCollapsed] = useState(false);
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [quickActions, setQuickActions] = useState<QuickAction[]>([]);
  const [agents, setAgents] = useState<Agent[]>([]);
  const [paletteOpen, setPaletteOpen] = useState(false);
  const [editorOpen, setEditorOpen] = useState(false);
  const [agentEditorOpen, setAgentEditorOpen] = useState(false);

  useEffect(() => {
    const saved = localStorage.getItem('llm-sidebar-state');
    if (saved === 'collapsed') setCollapsed(true);
  }, []);

  useEffect(() => {
    const handler = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key === '/') {
        e.preventDefault();
        setCollapsed(prev => {
          const next = !prev;
          localStorage.setItem('llm-sidebar-state', next ? 'collapsed' : 'expanded');
          return next;
        });
      }

      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        setPaletteOpen(true);
      }

      if (e.key === 'Escape') {
        setPaletteOpen(false);
      }
    };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, []);

  useEffect(() => {
    const load = async () => {
      await migrateV3ToV4();
      await seedBuiltinQuickActions();
      await seedBuiltinAgents();
      const rows = await listConversations({ archived: false, limit: 100 });
      const qas = await listQuickActions();
      const ags = await listAgents();
      setConversations(rows);
      setQuickActions(qas);
      setAgents(ags);
    };
    void load();
  }, [pathname]);

  const launchAgent = async (agent: Agent) => {
    const now = Date.now();
    const conv: Conversation = {
      id: crypto.randomUUID(),
      title: agent.name,
      model: agent.model,
      agentId: agent.id,
      systemPrompt: agent.systemPrompt,
      messageCount: 1,
      createdAt: now,
      updatedAt: now,
      pinned: false,
      archived: false,
      metadata: {
        totalTokens: 0,
        totalPrompts: 0,
        avgTokPerSec: 0,
        models: agent.model ? [agent.model] : [],
      },
    };

    await addConversation(conv);
    await addMessage({
      id: crypto.randomUUID(),
      conversationId: conv.id,
      role: 'assistant',
      content: agent.welcomeMessage || `Hi, I am ${agent.name}. How can I help?`,
      timestamp: now,
      model: agent.model,
    });
    await updateAgent(agent.id, { conversationCount: agent.conversationCount + 1 });

    setConversations(prev => [conv, ...prev]);
    setAgents(prev =>
      prev
        .map(item =>
          item.id === agent.id ? { ...item, conversationCount: item.conversationCount + 1 } : item
        )
        .sort((a, b) => b.conversationCount - a.conversationCount)
    );

    router.push(`/c/${conv.id}`);
  };

  const launchQuickAction = async (qa: QuickAction) => {
    const now = Date.now();
    const conv: Conversation = {
      id: crypto.randomUUID(),
      title: qa.name,
      model: qa.modelHint,
      systemPrompt: qa.systemPrompt,
      messageCount: 0,
      createdAt: now,
      updatedAt: now,
      pinned: false,
      archived: false,
      metadata: {
        totalTokens: 0,
        totalPrompts: 0,
        avgTokPerSec: 0,
        models: qa.modelHint ? [qa.modelHint] : [],
      },
    };

    await addConversation(conv);
    await updateQuickAction(qa.id, { usageCount: qa.usageCount + 1, lastUsed: now });
    setConversations(prev => [conv, ...prev]);
    setQuickActions(prev =>
      prev
        .map(item =>
          item.id === qa.id ? { ...item, usageCount: item.usageCount + 1, lastUsed: now } : item
        )
        .sort((a, b) => b.usageCount - a.usageCount)
    );
    const template = encodeURIComponent(qa.userTemplate);
    router.push(`/c/${conv.id}?template=${template}`);
  };

  const onNewConversation = async () => {
    const now = Date.now();
    const conv: Conversation = {
      id: crypto.randomUUID(),
      title: 'New Conversation',
      model: '',
      messageCount: 0,
      createdAt: now,
      updatedAt: now,
      pinned: false,
      archived: false,
      metadata: {
        totalTokens: 0,
        totalPrompts: 0,
        avgTokPerSec: 0,
        models: [],
      },
    };
    await addConversation(conv);
    setConversations(prev => [conv, ...prev]);
    router.push(`/c/${conv.id}`);
  };

  const activeConversationId = pathname.startsWith('/c/') ? pathname.slice(3) : undefined;

  return (
    <div className="flex min-h-screen bg-[var(--bg-canvas)]">
      <Sidebar
        collapsed={collapsed}
        conversations={conversations}
        onNewConversation={onNewConversation}
        activeConversationId={activeConversationId}
        onSelectConversation={id => router.push(`/c/${id}`)}
        quickActions={quickActions}
        onLaunchQuickAction={launchQuickAction}
        agents={agents}
        onLaunchAgent={launchAgent}
        onOpenQuickActionEditor={() => setEditorOpen(true)}
        onOpenAgentEditor={() => setAgentEditorOpen(true)}
      />
      <main className="min-w-0 flex-1">{children}</main>

      <CommandPalette
        open={paletteOpen}
        quickActions={quickActions}
        agents={agents}
        conversations={conversations}
        onClose={() => setPaletteOpen(false)}
        onSelectQuickAction={launchQuickAction}
        onSelectAgent={launchAgent}
        onSelectConversation={conversation => router.push(`/c/${conversation.id}`)}
        onSelectSystem={action => {
          if (action === 'mission-control') router.push('/mission-control');
          if (action === 'settings') {
            setAgentEditorOpen(true);
          }
          if (action === 'export') {
            alert('Data export will be wired in a follow-up phase.');
          }
        }}
      />

      <QuickActionEditor
        open={editorOpen}
        onClose={() => setEditorOpen(false)}
        onSave={async action => {
          await addQuickAction(action);
          const qas = await listQuickActions();
          setQuickActions(qas);
        }}
      />

      <AgentEditor
        open={agentEditorOpen}
        onClose={() => setAgentEditorOpen(false)}
        onSave={async agent => {
          const existing = agents.find(item => item.id === agent.id);
          if (existing) {
            await updateAgent(agent.id, agent);
          } else {
            await addAgent(agent);
          }
          const ags = await listAgents();
          setAgents(ags);
        }}
      />
    </div>
  );
}
