'use client';

import { useMemo, useState } from 'react';
import Fuse from 'fuse.js';
import type { Agent, Conversation, QuickAction } from '../../lib/types';

type CommandItem =
  | {
      type: 'qa';
      id: string;
      name: string;
      description: string;
      icon: string;
      payload: QuickAction;
    }
  | { type: 'agent'; id: string; name: string; description: string; icon: string; payload: Agent }
  | {
      type: 'conversation';
      id: string;
      name: string;
      description: string;
      icon: string;
      payload: Conversation;
    }
  | {
      type: 'system';
      id: string;
      name: string;
      description: string;
      icon: string;
      action: 'mission-control' | 'settings' | 'export';
    };

interface CommandPaletteProps {
  open: boolean;
  quickActions: QuickAction[];
  agents: Agent[];
  conversations: Conversation[];
  onClose: () => void;
  onSelectQuickAction: (qa: QuickAction) => void;
  onSelectAgent: (agent: Agent) => void;
  onSelectConversation: (conversation: Conversation) => void;
  onSelectSystem: (action: 'mission-control' | 'settings' | 'export') => void;
}

export function CommandPalette({
  open,
  quickActions,
  agents,
  conversations,
  onClose,
  onSelectQuickAction,
  onSelectAgent,
  onSelectConversation,
  onSelectSystem,
}: CommandPaletteProps) {
  const [query, setQuery] = useState('');

  const items = useMemo<CommandItem[]>(() => {
    const qaItems: CommandItem[] = quickActions.map(qa => ({
      type: 'qa',
      id: qa.id,
      name: qa.name,
      description: qa.description,
      icon: qa.icon,
      payload: qa,
    }));

    const agentItems: CommandItem[] = agents.map(agent => ({
      type: 'agent',
      id: agent.id,
      name: agent.name,
      description: agent.description,
      icon: agent.icon,
      payload: agent,
    }));

    const convItems: CommandItem[] = conversations.slice(0, 20).map(conv => ({
      type: 'conversation',
      id: conv.id,
      name: conv.title,
      description: conv.model || 'Conversation',
      icon: '💬',
      payload: conv,
    }));

    const systemItems: CommandItem[] = [
      {
        type: 'system',
        id: 'sys-mission-control',
        name: 'Mission Control',
        description: 'Open model and system dashboard',
        icon: '🎛️',
        action: 'mission-control',
      },
      {
        type: 'system',
        id: 'sys-settings',
        name: 'Settings',
        description: 'Open settings panel',
        icon: '⚙️',
        action: 'settings',
      },
      {
        type: 'system',
        id: 'sys-export',
        name: 'Export Data',
        description: 'Export workspace data',
        icon: '📦',
        action: 'export',
      },
    ];

    return [...qaItems, ...agentItems, ...convItems, ...systemItems];
  }, [quickActions, agents, conversations]);

  const results = useMemo(() => {
    if (!query.trim()) return items.slice(0, 15);
    const fuse = new Fuse(items, {
      keys: ['name', 'description'],
      threshold: 0.35,
      ignoreLocation: true,
      includeScore: true,
    });
    return fuse
      .search(query)
      .map(r => r.item)
      .slice(0, 15);
  }, [items, query]);

  if (!open) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-start justify-center bg-black/50 p-4"
      onClick={onClose}
    >
      <div
        className="mt-16 w-full max-w-2xl rounded-lg border border-white/10 bg-[var(--surface-card)] p-3 shadow-2xl"
        onClick={e => e.stopPropagation()}
      >
        <input
          autoFocus
          value={query}
          onChange={e => setQuery(e.target.value)}
          placeholder="Search actions, conversations, commands..."
          className="mb-3 w-full rounded-md border border-white/10 bg-[var(--surface-muted)] px-3 py-2 text-sm text-[var(--text-primary)] outline-none placeholder:text-[var(--text-tertiary)]"
          onKeyDown={e => {
            if (e.key === 'Escape') onClose();
          }}
        />

        <div className="max-h-[60vh] space-y-1 overflow-auto">
          {results.map(item => (
            <button
              key={`${item.type}-${item.id}`}
              type="button"
              onClick={() => {
                if (item.type === 'qa') onSelectQuickAction(item.payload);
                if (item.type === 'agent') onSelectAgent(item.payload);
                if (item.type === 'conversation') onSelectConversation(item.payload);
                if (item.type === 'system') onSelectSystem(item.action);
                onClose();
              }}
              className="flex w-full items-center gap-3 rounded-md px-3 py-2 text-left hover:bg-white/5"
            >
              <span className="text-base">{item.icon}</span>
              <div className="min-w-0 flex-1">
                <p className="truncate text-sm text-[var(--text-primary)]">{item.name}</p>
                <p className="truncate text-xs text-[var(--text-tertiary)]">{item.description}</p>
              </div>
              <span className="rounded border border-white/10 px-2 py-0.5 text-[10px] uppercase text-[var(--text-tertiary)]">
                {item.type}
              </span>
            </button>
          ))}
          {results.length === 0 && (
            <p className="px-2 py-6 text-center text-sm text-[var(--text-tertiary)]">No results</p>
          )}
        </div>
      </div>
    </div>
  );
}
