"use client";

import React, { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import {
  Search,
  X,
  UploadCloud,
  Sparkles,
  FileSpreadsheet,
  FileText,
  LayoutDashboard,
  Archive,
  Download,
  Settings,
  ArrowUpRight,
  Receipt,
  CornerDownLeft,
  ArrowDown,
  ArrowUp,
} from "lucide-react";
import { ProcessedReceipt } from "@/lib/schema/receipt";
import { fetchServerReceipts, getCurrentUserId } from "@/lib/storage/server";
import { useI18n } from "@/lib/i18n/context";

interface SpotlightDialogProps {
  isOpen: boolean;
  onClose: () => void;
  onTriggerScan?: () => void;
  onLoadDemo?: () => void;
  onSelectReceipt?: (receipt: ProcessedReceipt) => void;
  receipts?: ProcessedReceipt[];
}

interface CommandItem {
  id: string;
  title: string;
  subtitle?: string;
  category: "actions" | "receipts" | "navigation";
  icon: React.ElementType;
  badge?: string;
  action: () => void;
}

export function SpotlightDialog({
  isOpen,
  onClose,
  onTriggerScan,
  onLoadDemo,
  onSelectReceipt,
  receipts: propReceipts,
}: SpotlightDialogProps) {
  const router = useRouter();
  const { language } = useI18n();
  const isDe = language === "de";

  const [query, setQuery] = useState("");
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [localReceipts, setLocalReceipts] = useState<ProcessedReceipt[]>([]);
  const inputRef = useRef<HTMLInputElement>(null);
  const listRef = useRef<HTMLDivElement>(null);

  // Load receipts if not provided via props
  useEffect(() => {
    if (isOpen) {
      async function load() {
        if (propReceipts && propReceipts.length > 0) {
          setLocalReceipts(propReceipts);
        } else {
          const uid = await getCurrentUserId();
          const data = await fetchServerReceipts(uid);
          setLocalReceipts(data);
        }
      }
      load();
      setQuery("");
      setSelectedIndex(0);
      setTimeout(() => {
        inputRef.current?.focus();
      }, 50);
    }
  }, [isOpen, propReceipts]);

  // Build command items
  const allItems: CommandItem[] = [];

  // 1. Quick Actions
  const actionItems: CommandItem[] = [
    {
      id: "action-upload",
      title: isDe ? "+ Neuen Beleg hochladen / scannen" : "+ Upload / scan new receipt",
      subtitle: isDe ? "Öffnet Datei-Dialog für Kassenbon-Upload" : "Opens file picker for receipt upload",
      category: "actions",
      icon: UploadCloud,
      badge: "SCAN",
      action: () => {
        onClose();
        if (onTriggerScan) {
          onTriggerScan();
        } else {
          router.push("/dashboard");
        }
      },
    },
    {
      id: "action-demo",
      title: isDe ? "Demo-Belege laden" : "Load demo receipts",
      subtitle: isDe ? "Generiert Aral, Rewe & Trattoria Musterbelege" : "Seeds Aral, Rewe & Trattoria sample receipts",
      category: "actions",
      icon: Sparkles,
      badge: "DEMO",
      action: () => {
        onClose();
        if (onLoadDemo) {
          onLoadDemo();
        } else {
          router.push("/dashboard");
        }
      },
    },
    {
      id: "action-excel",
      title: isDe ? "Excel-Export (.xlsx) erstellen" : "Generate Excel export (.xlsx)",
      subtitle: isDe ? "Dual-Sheet Arbeitsmappe mit dynamischen =SUM() Formeln" : "Dual-sheet workbook with dynamic =SUM() formulas",
      category: "actions",
      icon: FileSpreadsheet,
      badge: "XLSX",
      action: () => {
        onClose();
        router.push("/dashboard/export");
      },
    },
    {
      id: "action-csv",
      title: isDe ? "CSV exportieren" : "Export CSV",
      subtitle: isDe ? "Semikolon, Dezimalkomma, UTF-8 BOM – öffnet in Excel" : "Semicolon, decimal commas, UTF-8 BOM – opens in Excel",
      category: "actions",
      icon: FileText,
      badge: "CSV",
      action: () => {
        onClose();
        router.push("/dashboard/export");
      },
    },
  ];

  // 2. Receipt Items (filtered by query)
  const receiptItems: CommandItem[] = localReceipts.map((r) => ({
    id: `receipt-${r.id}`,
    title: `${r.merchant?.name || (isDe ? "Unbekannter Händler" : "Unknown Merchant")} • ${r.totalAmount?.value ? r.totalAmount.value.toFixed(2) + " €" : ""}`,
    subtitle: `${r.date?.isoDate || (isDe ? "Kein Datum" : "No date")} • ${r.suggestedCategory || (isDe ? "Beleg" : "Receipt")} ${r.receiptNumber ? "• #" + r.receiptNumber : ""}`,
    category: "receipts" as const,
    icon: Receipt,
    badge: r.validation?.isMathValid ? "VALID" : "REVIEW",
    action: () => {
      onClose();
      if (onSelectReceipt) {
        onSelectReceipt(r);
      } else {
        router.push("/dashboard/activity");
      }
    },
  }));

  // 3. Navigation Links
  const navItems: CommandItem[] = [
    {
      id: "nav-overview",
      title: isDe ? "Dashboard Übersicht" : "Dashboard Overview",
      subtitle: "/dashboard",
      category: "navigation",
      icon: LayoutDashboard,
      badge: "GOTO",
      action: () => {
        onClose();
        router.push("/dashboard");
      },
    },
    {
      id: "nav-activity",
      title: isDe ? "Scan-Archiv & Belege" : "Scan Activity & Archive",
      subtitle: "/dashboard/activity",
      category: "navigation",
      icon: Archive,
      badge: "GOTO",
      action: () => {
        onClose();
        router.push("/dashboard/activity");
      },
    },
    {
      id: "nav-export",
      title: isDe ? "Export-Zentrale (Excel & CSV)" : "Export Dispatcher (Excel & CSV)",
      subtitle: "/dashboard/export",
      category: "navigation",
      icon: Download,
      badge: "GOTO",
      action: () => {
        onClose();
        router.push("/dashboard/export");
      },
    },
    {
      id: "nav-settings",
      title: isDe ? "System- & KI-Einstellungen" : "System & AI Settings",
      subtitle: "/dashboard/settings",
      category: "navigation",
      icon: Settings,
      badge: "GOTO",
      action: () => {
        onClose();
        router.push("/dashboard/settings");
      },
    },
    {
      id: "nav-landing",
      title: isDe ? "Landing Page & Hero Scanner" : "Landing Page & Hero Scanner",
      subtitle: "/",
      category: "navigation",
      icon: ArrowUpRight,
      badge: "HOME",
      action: () => {
        onClose();
        router.push("/");
      },
    },
  ];

  // Filter items based on query
  const q = query.toLowerCase().trim();
  const filteredActions = actionItems.filter(
    (item) => item.title.toLowerCase().includes(q) || item.subtitle?.toLowerCase().includes(q)
  );
  const filteredReceipts = receiptItems.filter(
    (item) => item.title.toLowerCase().includes(q) || item.subtitle?.toLowerCase().includes(q)
  );
  const filteredNav = navItems.filter(
    (item) => item.title.toLowerCase().includes(q) || item.subtitle?.toLowerCase().includes(q)
  );

  const filteredItems = [...filteredActions, ...filteredReceipts, ...filteredNav];

  // Keyboard navigation within dialog
  useEffect(() => {
    if (!isOpen) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onClose();
      } else if (e.key === "ArrowDown") {
        e.preventDefault();
        setSelectedIndex((prev) =>
          filteredItems.length > 0 ? (prev + 1) % filteredItems.length : 0
        );
      } else if (e.key === "ArrowUp") {
        e.preventDefault();
        setSelectedIndex((prev) =>
          filteredItems.length > 0
            ? (prev - 1 + filteredItems.length) % filteredItems.length
            : 0
        );
      } else if (e.key === "Enter") {
        e.preventDefault();
        if (filteredItems[selectedIndex]) {
          filteredItems[selectedIndex].action();
        }
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [isOpen, filteredItems, selectedIndex, onClose]);

  // Adjust selection when query changes
  useEffect(() => {
    setSelectedIndex(0);
  }, [query]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center pt-16 sm:pt-24 p-4 bg-black/70 backdrop-blur-sm animate-fade-in font-sans">
      <div className="relative w-full max-w-2xl bg-white border-2 border-black overflow-hidden">
        {/* Search Header Bar */}
        <div className="flex items-center px-4 py-3.5 border-b border-[#E2E8F0] bg-[#F8FAFC]">
          <Search className="w-4 h-4 text-black shrink-0 mr-3" />
          <input
            ref={inputRef}
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder={
              isDe
                ? "Befehl, Beleg, Händler oder Seite suchen..."
                : "Type a command, merchant, receipt or page..."
            }
            className="w-full bg-transparent text-sm text-black placeholder:text-[#94A3B8] focus:outline-none font-sans"
          />
          {query && (
            <button
              onClick={() => setQuery("")}
              className="p-1 text-[#94A3B8] hover:text-black mr-2 font-mono text-xs"
            >
              <X className="w-3.5 h-3.5" />
            </button>
          )}
          <kbd
            onClick={onClose}
            className="cursor-pointer font-mono text-[10px] uppercase tracking-wider text-[#64748B] bg-white border border-[#E2E8F0] px-1.5 py-0.5 hover:border-black hover:text-black transition-colors shrink-0"
          >
            ESC
          </kbd>
        </div>

        {/* Results List */}
        <div
          ref={listRef}
          className="max-h-[60vh] overflow-y-auto divide-y divide-[#F1F5F9] p-2"
        >
          {filteredItems.length === 0 ? (
            <div className="py-12 text-center text-[#94A3B8] font-mono text-xs">
              <Search className="w-8 h-8 mx-auto mb-2 opacity-30 text-black" />
              <p>
                {isDe
                  ? `Keine Ergebnisse für "${query}" gefunden`
                  : `No results found for "${query}"`}
              </p>
            </div>
          ) : (
            <>
              {/* Group 1: Actions */}
              {filteredActions.length > 0 && (
                <div className="pb-2">
                  <div className="px-3 py-1.5 font-mono text-[10px] uppercase tracking-caps text-[#64748B] font-bold">
                    {isDe ? "SCHNELLAKTIONEN" : "QUICK ACTIONS"}
                  </div>
                  {filteredActions.map((item) => {
                    const itemIdx = filteredItems.findIndex((x) => x.id === item.id);
                    const isSelected = itemIdx === selectedIndex;
                    const Icon = item.icon;
                    return (
                      <div
                        key={item.id}
                        onClick={item.action}
                        onMouseEnter={() => setSelectedIndex(itemIdx)}
                        className={`flex items-center justify-between px-3 py-2.5 cursor-pointer transition-colors ${
                          isSelected
                            ? "bg-[#EEF4FC] border-l-2 border-black"
                            : "hover:bg-[#F8FAFC]"
                        }`}
                      >
                        <div className="flex items-center gap-3 min-w-0">
                          <div
                            className={`w-7 h-7 flex items-center justify-center shrink-0 ${
                              isSelected
                                ? "bg-black text-white"
                                : "bg-[#F8FAFC] border border-[#E2E8F0] text-black"
                            }`}
                          >
                            <Icon className="w-3.5 h-3.5" />
                          </div>
                          <div className="min-w-0">
                            <p className="text-xs font-semibold text-black truncate">
                              {item.title}
                            </p>
                            {item.subtitle && (
                              <p className="text-[11px] text-[#64748B] truncate font-sans">
                                {item.subtitle}
                              </p>
                            )}
                          </div>
                        </div>
                        {item.badge && (
                          <span className="font-mono text-[9px] uppercase tracking-wider bg-white border border-[#E2E8F0] px-1.5 py-0.5 text-[#475569] shrink-0 ml-2">
                            {item.badge}
                          </span>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}

              {/* Group 2: Receipts */}
              {filteredReceipts.length > 0 && (
                <div className="py-2">
                  <div className="px-3 py-1.5 font-mono text-[10px] uppercase tracking-caps text-[#64748B] font-bold">
                    {isDe ? "BELEGE & ARCHIV" : "RECEIPTS & ARCHIVE"}
                  </div>
                  {filteredReceipts.map((item) => {
                    const itemIdx = filteredItems.findIndex((x) => x.id === item.id);
                    const isSelected = itemIdx === selectedIndex;
                    const Icon = item.icon;
                    return (
                      <div
                        key={item.id}
                        onClick={item.action}
                        onMouseEnter={() => setSelectedIndex(itemIdx)}
                        className={`flex items-center justify-between px-3 py-2.5 cursor-pointer transition-colors ${
                          isSelected
                            ? "bg-[#EEF4FC] border-l-2 border-black"
                            : "hover:bg-[#F8FAFC]"
                        }`}
                      >
                        <div className="flex items-center gap-3 min-w-0">
                          <div
                            className={`w-7 h-7 flex items-center justify-center shrink-0 ${
                              isSelected
                                ? "bg-black text-white"
                                : "bg-[#F8FAFC] border border-[#E2E8F0] text-black"
                            }`}
                          >
                            <Icon className="w-3.5 h-3.5" />
                          </div>
                          <div className="min-w-0">
                            <p className="text-xs font-semibold text-black truncate font-mono">
                              {item.title}
                            </p>
                            {item.subtitle && (
                              <p className="text-[11px] text-[#64748B] truncate font-sans">
                                {item.subtitle}
                              </p>
                            )}
                          </div>
                        </div>
                        {item.badge && (
                          <span
                            className={`font-mono text-[9px] uppercase tracking-wider px-1.5 py-0.5 shrink-0 ml-2 ${
                              item.badge === "VALID"
                                ? "bg-emerald-50 text-emerald-700 border border-emerald-300"
                                : "bg-amber-50 text-amber-800 border border-amber-300"
                            }`}
                          >
                            {item.badge}
                          </span>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}

              {/* Group 3: Navigation */}
              {filteredNav.length > 0 && (
                <div className="pt-2">
                  <div className="px-3 py-1.5 font-mono text-[10px] uppercase tracking-caps text-[#64748B] font-bold">
                    {isDe ? "SEITEN & NAVIGATION" : "PAGES & NAVIGATION"}
                  </div>
                  {filteredNav.map((item) => {
                    const itemIdx = filteredItems.findIndex((x) => x.id === item.id);
                    const isSelected = itemIdx === selectedIndex;
                    const Icon = item.icon;
                    return (
                      <div
                        key={item.id}
                        onClick={item.action}
                        onMouseEnter={() => setSelectedIndex(itemIdx)}
                        className={`flex items-center justify-between px-3 py-2.5 cursor-pointer transition-colors ${
                          isSelected
                            ? "bg-[#EEF4FC] border-l-2 border-black"
                            : "hover:bg-[#F8FAFC]"
                        }`}
                      >
                        <div className="flex items-center gap-3 min-w-0">
                          <div
                            className={`w-7 h-7 flex items-center justify-center shrink-0 ${
                              isSelected
                                ? "bg-black text-white"
                                : "bg-[#F8FAFC] border border-[#E2E8F0] text-black"
                            }`}
                          >
                            <Icon className="w-3.5 h-3.5" />
                          </div>
                          <div className="min-w-0">
                            <p className="text-xs font-semibold text-black truncate">
                              {item.title}
                            </p>
                            {item.subtitle && (
                              <p className="text-[11px] text-[#64748B] truncate font-mono">
                                {item.subtitle}
                              </p>
                            )}
                          </div>
                        </div>
                        {item.badge && (
                          <span className="font-mono text-[9px] uppercase tracking-wider bg-white border border-[#E2E8F0] px-1.5 py-0.5 text-[#475569] shrink-0 ml-2">
                            {item.badge}
                          </span>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}
            </>
          )}
        </div>

        {/* Footer Shortcut Bar */}
        <div className="px-4 py-2.5 bg-[#F8FAFC] border-t border-[#E2E8F0] flex items-center justify-between text-[11px] font-mono text-[#64748B]">
          <div className="flex items-center gap-4">
            <span className="flex items-center gap-1">
              <kbd className="bg-white border border-[#E2E8F0] px-1 py-0.2 text-[10px]">↑</kbd>
              <kbd className="bg-white border border-[#E2E8F0] px-1 py-0.2 text-[10px]">↓</kbd>
              <span>{isDe ? "Navigieren" : "Navigate"}</span>
            </span>
            <span className="flex items-center gap-1">
              <kbd className="bg-white border border-[#E2E8F0] px-1.5 py-0.2 text-[10px]">↵</kbd>
              <span>{isDe ? "Auswählen" : "Select"}</span>
            </span>
          </div>
          <div className="flex items-center gap-1">
            <kbd className="bg-white border border-[#E2E8F0] px-1.5 py-0.2 text-[10px]">ESC</kbd>
            <span>{isDe ? "Schließen" : "Close"}</span>
          </div>
        </div>
      </div>
    </div>
  );
}
