"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import {
  ArrowRight,
  Award,
  BellRing,
  Bot,
  Calendar,
  CheckSquare,
  FileText,
  FolderKanban,
  MessageSquareText,
  Search,
  Sparkles,
  Timer,
  Wallet,
  Network,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { useUIStore } from "@/stores/ui-store";
import { useGlobalSearch, type GlobalSearchResult } from "@/hooks/use-global-search";

/* ─── Quick Actions ──────────────────────────────────────────────────────── */

const QUICK_ACTIONS = [
  { id: "qa-command-center", label: "Command Center", icon: Sparkles, href: "/command-center", hint: "C" },
  { id: "qa-task",    label: "New Task",          icon: CheckSquare,      href: "/tasks",    hint: "T" },
  { id: "qa-project", label: "New Project",       icon: FolderKanban,     href: "/projects", hint: "P" },
  { id: "qa-note",   label: "New Note",           icon: FileText,         href: "/notes",    hint: "N" },
  { id: "qa-event",  label: "New Event",          icon: Calendar,         href: "/calendar", hint: "E" },
  { id: "qa-reminder", label: "New Reminder",      icon: BellRing,         href: "/reminders", hint: "R" },
  { id: "qa-life-map", label: "Life Map",          icon: Network,          href: "/life-map", hint: "L" },
  { id: "qa-chat",   label: "New Message",        icon: MessageSquareText, href: "/chat",    hint: "M" },
  { id: "qa-focus",  label: "Focus Hub",          icon: Timer,            href: "/focus", hint: "F", action: "focus" },
  { id: "qa-achievements", label: "Achievements", icon: Award,           href: "/achievements", hint: "" },
  { id: "qa-expense","label": "Log Expense",       icon: Wallet,           href: "/finances", hint: "" },
  { id: "qa-ai",     label: "Ask AI",             icon: Bot,              href: "/ai",       hint: "A" },
];

/* ─── AI Prompt Suggestions ─────────────────────────────────────────────── */

const AI_PROMPTS = [
  "Plan my day",
  "Summarize open projects",
  "Show overdue tasks",
  "Prepare weekly review",
  "Show cashflow this month",
  "Create tasks from meeting",
];

type QuickActionItem = (typeof QUICK_ACTIONS)[number] & {
  title: string;
  subtitle: string;
  section: "Actions";
};

function getItemAction(item: GlobalSearchResult | QuickActionItem) {
  return "action" in item ? item.action : undefined;
}

/* ─── Component ─────────────────────────────────────────────────────────── */

export function CommandPalette() {
  const { commandPaletteOpen, setCommandPaletteOpen } = useUIStore();
  const [query, setQuery] = useState("");
  const [selectedIndex, setSelectedIndex] = useState(0);
  const inputRef = useRef<HTMLInputElement>(null);
  const router = useRouter();
  const { pageResults, results, searching } = useGlobalSearch(query);

  const mode = useMemo<"default" | "ai">(() => {
    const q = query.trim().toLowerCase();
    const isAI =
      q.startsWith("ai ") ||
      q.startsWith("> ") ||
      q.startsWith("ask ") ||
      q.startsWith("plan ") ||
      q.startsWith("show ") ||
      q.startsWith("summarize ") ||
      q.startsWith("create ") ||
      q.startsWith("prepare ") ||
      q.startsWith("log ");

    return isAI ? "ai" : "default";
  }, [query]);

  /* keyboard shortcut ─────────────────────────────────────────────────── */
  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        setCommandPaletteOpen(!commandPaletteOpen);
      }
    }
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [commandPaletteOpen, setCommandPaletteOpen]);

  /* reset on open ─────────────────────────────────────────────────────── */
  useEffect(() => {
    if (!commandPaletteOpen) return;
    const t = setTimeout(() => {
      setQuery("");
      setSelectedIndex(0);
      inputRef.current?.focus();
    }, 0);
    return () => clearTimeout(t);
  }, [commandPaletteOpen]);

  function navigate(href: string, action?: string) {
    setCommandPaletteOpen(false);
    if (action === "focus") {
      router.push("/focus");
      return;
    }
    router.push(href);
  }

  function handleAIQuery(prompt: string) {
    setCommandPaletteOpen(false);
    router.push(`/ai?q=${encodeURIComponent(prompt)}`);
  }

  /* merged search results ─────────────────────────────────────────────── */
  const searchResults = useMemo(() => {
    if (!query.trim()) return [];
    return [...pageResults, ...results].slice(0, 8);
  }, [pageResults, results, query]);

  const allItems = useMemo<Array<GlobalSearchResult | QuickActionItem>>(() => {
    if (mode === "ai") return [];
    if (query.trim()) return searchResults;
    return QUICK_ACTIONS.map((a) => ({ ...a, title: a.label, subtitle: "", section: "Actions" as const, href: a.href }));
  }, [mode, query, searchResults]);

  function handleKeyDown(e: React.KeyboardEvent) {
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setSelectedIndex((i) => (i + 1) % Math.max(allItems.length, 1));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setSelectedIndex((i) => (i - 1 + Math.max(allItems.length, 1)) % Math.max(allItems.length, 1));
    } else if (e.key === "Enter") {
      e.preventDefault();
      if (mode === "ai" && query.trim()) {
        handleAIQuery(query.trim());
      } else if (allItems[selectedIndex]) {
        const selectedItem = allItems[selectedIndex];
        navigate(selectedItem.href, getItemAction(selectedItem));
      }
    } else if (e.key === "Escape") {
      setCommandPaletteOpen(false);
    }
  }

  if (!commandPaletteOpen) return null;

  const showDefault = !query.trim() && mode === "default";
  const showAI      = mode === "ai";
  const showResults = !!query.trim() && mode === "default";

  return (
    <div className="fixed inset-0 z-[9998] flex items-start justify-center pt-[12vh]" onClick={() => setCommandPaletteOpen(false)}>
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/70 backdrop-blur-sm" />

      {/* Panel */}
      <div
        className="relative z-[9999] w-full max-w-[640px] overflow-hidden rounded-2xl border border-white/[0.08] bg-[#0e0e12] shadow-2xl shadow-black/80"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Input Row */}
        <div className="flex items-center gap-3 border-b border-white/[0.06] px-4">
          {mode === "ai"
            ? <Sparkles className="h-4 w-4 shrink-0 text-indigo-400" />
            : <Search className="h-4 w-4 shrink-0 text-white/25" />
          }
          <input
            ref={inputRef}
            value={query}
            onChange={(e) => { setQuery(e.target.value); setSelectedIndex(0); }}
            onKeyDown={handleKeyDown}
            placeholder={mode === "ai" ? "Ask AI anything about your workspace…" : "Search or type a command…"}
            className={cn(
              "flex-1 bg-transparent py-4 text-[14px] outline-none placeholder:text-white/20",
              mode === "ai" ? "text-indigo-200" : "text-white/80"
            )}
          />
          <div className="flex items-center gap-2">
            {mode === "ai" && (
              <span className="rounded-md bg-indigo-500/15 px-2 py-0.5 text-[10px] font-semibold text-indigo-400">AI</span>
            )}
            <kbd className="rounded bg-white/[0.05] px-1.5 py-0.5 font-mono text-[10px] text-white/20">ESC</kbd>
          </div>
        </div>

        {/* Body */}
        <div className="max-h-[400px] overflow-y-auto">

          {/* ── Default: Quick Actions ─────────────────────────────── */}
          {showDefault && (
            <div className="p-3">
              <p className="mb-2 px-2 text-[10px] font-bold uppercase tracking-[0.16em] text-white/20">Quick Actions</p>
              <div className="grid grid-cols-1 gap-1 sm:grid-cols-2">
                {QUICK_ACTIONS.map((action, i) => (
                  <button
                    key={action.id}
                    onClick={() => navigate(action.href, action.action)}
                    className={cn(
                      "flex items-center gap-3 rounded-xl px-3 py-2.5 text-left transition-all",
                      i === selectedIndex
                        ? "bg-white/[0.07] text-white"
                        : "text-white/50 hover:bg-white/[0.05] hover:text-white/80"
                    )}
                  >
                    <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-white/[0.05]">
                      <action.icon className="h-3.5 w-3.5" />
                    </div>
                    <span className="text-[13px] font-medium">{action.label}</span>
                  </button>
                ))}
              </div>

              {/* AI Prompts */}
              <div className="mt-4 border-t border-white/[0.05] pt-3">
                <p className="mb-2 px-2 text-[10px] font-bold uppercase tracking-[0.16em] text-indigo-400/50">
                  <Sparkles className="mr-1.5 inline-block h-3 w-3" />
                  AI Commands
                </p>
                <div className="space-y-0.5">
                  {AI_PROMPTS.map((prompt) => (
                    <button
                      key={prompt}
                      onClick={() => handleAIQuery(prompt)}
                      className="flex w-full items-center gap-3 rounded-xl px-3 py-2 text-left text-[13px] text-white/35 transition-all hover:bg-indigo-500/10 hover:text-indigo-300"
                    >
                      <Sparkles className="h-3.5 w-3.5 shrink-0 text-indigo-400/40" />
                      {prompt}
                    </button>
                  ))}
                </div>
              </div>

              {/* Footer hint */}
              <div className="mt-3 flex items-center gap-3 border-t border-white/[0.04] px-2 pt-3 text-[11px] text-white/15">
                <span><kbd className="font-mono">↑↓</kbd> navigate</span>
                <span><kbd className="font-mono">↵</kbd> select</span>
                <span>type <code className="text-white/25">ai …</code> for AI</span>
                <span className="ml-auto"><kbd className="font-mono">⌘K</kbd> toggle</span>
              </div>
            </div>
          )}

          {/* ── AI Mode ─────────────────────────────────────────────── */}
          {showAI && (
            <div className="p-3">
              <div className="rounded-xl border border-indigo-500/20 bg-indigo-500/5 p-4">
                <div className="flex items-start gap-3">
                  <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-indigo-500/15">
                    <Sparkles className="h-4 w-4 text-indigo-400" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <p className="text-[13px] font-semibold text-white/80">AI Command detected</p>
                    <p className="mt-0.5 text-[12px] text-white/40">Press Enter to send to AI Assistant</p>
                    <p className="mt-2 rounded-lg bg-white/[0.04] px-3 py-2 text-[13px] text-indigo-300 italic">
                      &quot;{query}&quot;
                    </p>
                  </div>
                </div>
              </div>
              <div className="mt-3 space-y-0.5">
                <p className="mb-2 px-2 text-[10px] font-bold uppercase tracking-[0.16em] text-white/20">Or try</p>
                {AI_PROMPTS.filter(p => !query.toLowerCase().includes(p.toLowerCase().split(" ")[0])).slice(0, 3).map((prompt) => (
                  <button
                    key={prompt}
                    onClick={() => handleAIQuery(prompt)}
                    className="flex w-full items-center gap-3 rounded-xl px-3 py-2 text-left text-[13px] text-white/35 transition-all hover:bg-indigo-500/10 hover:text-indigo-300"
                  >
                    <Sparkles className="h-3.5 w-3.5 shrink-0 text-indigo-400/40" />
                    {prompt}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* ── Search Results ───────────────────────────────────────── */}
          {showResults && (
            <div className="p-2">
              {searching ? (
                <div className="flex items-center gap-2 px-4 py-8 text-[13px] text-white/25">
                  <div className="h-3.5 w-3.5 animate-spin rounded-full border border-white/20 border-t-white/60" />
                  Searching workspace…
                </div>
              ) : searchResults.length === 0 ? (
                <div className="px-4 py-8 text-center text-[13px] text-white/25">
                  No results — press Enter to ask AI
                </div>
              ) : (
                <>
                  {/* Group by section */}
                  {Array.from(new Set(searchResults.map(r => r.section))).map(section => (
                    <div key={section} className="mb-1">
                      <p className="px-3 py-1.5 text-[10px] font-bold uppercase tracking-[0.16em] text-white/20">{section}</p>
                      {searchResults.filter(r => r.section === section).map((item) => {
                        const globalIdx = searchResults.indexOf(item);
                        return (
                          <button
                            key={item.id}
                            onClick={() => navigate(item.href)}
                            className={cn(
                              "flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left transition-all",
                              globalIdx === selectedIndex
                                ? "bg-white/[0.07] text-white"
                                : "text-white/50 hover:bg-white/[0.05] hover:text-white/80"
                            )}
                          >
                            <item.icon className="h-4 w-4 shrink-0 text-white/30" />
                            <div className="min-w-0 flex-1">
                              <p className="truncate text-[13px] font-medium">{item.title}</p>
                              {item.subtitle && (
                                <p className="truncate text-[11px] text-white/30">{item.subtitle}</p>
                              )}
                            </div>
                            <ArrowRight className="h-3 w-3 shrink-0 text-white/15" />
                          </button>
                        );
                      })}
                    </div>
                  ))}

                  {/* Ask AI fallback */}
                  <div className="border-t border-white/[0.05] p-2 mt-1">
                    <button
                      onClick={() => handleAIQuery(query)}
                      className="flex w-full items-center gap-3 rounded-xl px-3 py-2.5 text-left text-[13px] text-white/30 transition-all hover:bg-indigo-500/10 hover:text-indigo-300"
                    >
                      <Sparkles className="h-4 w-4 shrink-0 text-indigo-400/40" />
                      <span>Ask AI: <span className="text-white/50">&quot;{query}&quot;</span></span>
                    </button>
                  </div>
                </>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
