'use client';

import Link from 'next/link';
import { useMemo, useState } from 'react';
import {
  FolderKanban,
  LayoutDashboard,
  Plus,
  Search,
  Settings,
  Sparkles,
  UserRound,
} from 'lucide-react';
import type { Agent, Conversation, QuickAction } from '../../lib/types';
import type { ReactNode } from 'react';
import { ConversationList } from './ConversationList';

interface SidebarProps {
  collapsed: boolean;
  conversations: Conversation[];
  onNewConversation: () => void;
  activeConversationId?: string;
  onSelectConversation: (id: string) => void;
  quickActions: QuickAction[];
  onLaunchQuickAction: (qa: QuickAction) => void;
  agents: Agent[];
  onLaunchAgent: (agent: Agent) => void;
  onOpenQuickActionEditor: () => void;
  onOpenAgentEditor: () => void;
}

export function Sidebar({
  collapsed,
  conversations,
  onNewConversation,
  activeConversationId,
  onSelectConversation,
  quickActions,
  onLaunchQuickAction,
  agents,
  onLaunchAgent,
  onOpenQuickActionEditor,
  onOpenAgentEditor,
}: SidebarProps) {
  const [query, setQuery] = useState('');
  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return conversations;
    return conversations.filter(c => c.title.toLowerCase().includes(q));
  }, [conversations, query]);
  const topQuickActions = useMemo(() => quickActions.slice(0, 5), [quickActions]);
  const topAgents = useMemo(() => agents.slice(0, 6), [agents]);

  return (
    <aside
      className="h-screen border-r border-white/10 bg-[var(--bg-elevated)] text-[var(--text-primary)] transition-all"
      style={{ width: collapsed ? 72 : 240 }}
    >
      <div className="flex h-full flex-col gap-4 p-3">
        <button
          type="button"
          onClick={onNewConversation}
          className="inline-flex items-center justify-center gap-2 rounded-md bg-[var(--accent-primary)] px-3 py-2 text-sm font-medium text-white hover:opacity-90"
          title="New Conversation"
        >
          <Plus size={16} />
          {!collapsed && <span>New Conversation</span>}
        </button>

        <nav className="space-y-1 text-sm">
          <SidebarNavItem
            collapsed={collapsed}
            icon={<Sparkles size={16} />}
            label="Quick Actions"
            onClick={onOpenQuickActionEditor}
          />
          <SidebarNavItem
            collapsed={collapsed}
            icon={<UserRound size={16} />}
            label="My Agents"
            onClick={onOpenAgentEditor}
          />
          <SidebarNavItem
            collapsed={collapsed}
            icon={<FolderKanban size={16} />}
            label="Projects"
          />
        </nav>

        {!collapsed && topAgents.length > 0 && (
          <section>
            <p className="mb-1 text-[10px] uppercase tracking-wide text-[var(--text-tertiary)]">
              My Agents
            </p>
            <div className="flex flex-wrap gap-1">
              {topAgents.map(agent => (
                <button
                  key={agent.id}
                  type="button"
                  onClick={() => onLaunchAgent(agent)}
                  className="rounded border border-white/10 bg-[var(--surface-muted)] px-2 py-1 text-xs text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
                  title={`${agent.name}: ${agent.description}`}
                >
                  {agent.icon} {agent.name}
                </button>
              ))}
            </div>
          </section>
        )}

        {!collapsed && topQuickActions.length > 0 && (
          <section>
            <p className="mb-1 text-[10px] uppercase tracking-wide text-[var(--text-tertiary)]">
              Frequently-used Quick Actions
            </p>
            <div className="space-y-1">
              {topQuickActions.map(qa => (
                <button
                  key={qa.id}
                  type="button"
                  onClick={() => onLaunchQuickAction(qa)}
                  className="flex w-full items-center gap-2 rounded px-2 py-1 text-left text-xs text-[var(--text-secondary)] hover:bg-white/5 hover:text-[var(--text-primary)]"
                >
                  <span>{qa.icon}</span>
                  <span className="truncate">{qa.name}</span>
                </button>
              ))}
            </div>
          </section>
        )}

        <div className="my-1 border-t border-white/10" />

        <div className="min-h-0 flex-1 overflow-auto">
          {!collapsed && (
            <div className="mb-2">
              <label className="mb-1 block text-[10px] uppercase tracking-wide text-[var(--text-tertiary)]">
                Conversations
              </label>
              <div className="flex items-center gap-2 rounded-md border border-white/10 bg-[var(--surface-muted)] px-2 py-1">
                <Search size={12} className="text-[var(--text-tertiary)]" />
                <input
                  value={query}
                  onChange={e => setQuery(e.target.value)}
                  placeholder="Search"
                  className="w-full bg-transparent text-xs text-[var(--text-primary)] outline-none placeholder:text-[var(--text-tertiary)]"
                />
              </div>
            </div>
          )}
          {!collapsed && (
            <ConversationList
              conversations={filtered}
              activeId={activeConversationId}
              onSelect={onSelectConversation}
            />
          )}
        </div>

        <div className="mt-auto space-y-1 border-t border-white/10 pt-2 text-sm">
          <Link
            href="/mission-control"
            className="flex items-center gap-2 rounded px-2 py-1 text-[var(--text-secondary)] hover:bg-white/5 hover:text-[var(--text-primary)]"
          >
            <LayoutDashboard size={16} />
            {!collapsed && <span>Mission Control</span>}
          </Link>
          <button
            type="button"
            className="flex w-full items-center gap-2 rounded px-2 py-1 text-[var(--text-secondary)] hover:bg-white/5 hover:text-[var(--text-primary)]"
          >
            <Settings size={16} />
            {!collapsed && <span>Settings</span>}
          </button>
        </div>
      </div>
    </aside>
  );
}

function SidebarNavItem({
  collapsed,
  icon,
  label,
  onClick,
}: {
  collapsed: boolean;
  icon: ReactNode;
  label: string;
  onClick?: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="flex w-full items-center gap-2 rounded px-2 py-1 text-[var(--text-secondary)] hover:bg-white/5 hover:text-[var(--text-primary)]"
      title={label}
    >
      {icon}
      {!collapsed && <span>{label}</span>}
    </button>
  );
}
