"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { Search, ArrowRight, Loader2, Compass, Users, FileText, CheckSquare } from "lucide-react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { StatusBadge } from "@/components/shared/status-badge";

interface SearchResultItem {
  id: string;
  category: "Navigation" | "Employee" | "Request" | "Task";
  title: string;
  subtitle: string;
  href: string;
  badge?: string;
}

interface GlobalSearchModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function GlobalSearchModal({ open, onOpenChange }: GlobalSearchModalProps) {
  const router = useRouter();
  const [query, setQuery] = React.useState("");
  const [results, setResults] = React.useState<SearchResultItem[]>([]);
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        onOpenChange(!open);
      }
    };
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [open, onOpenChange]);

  React.useEffect(() => {
    if (!open) return;
    let active = true;
    const timer = setTimeout(async () => {
      setLoading(true);
      try {
        const res = await fetch(`/api/v1/search?q=${encodeURIComponent(query)}`);
        if (!res.ok) return;
        const json = await res.json();
        if (active && Array.isArray(json.data)) {
          setResults(json.data);
        }
      } finally {
        if (active) setLoading(false);
      }
    }, 160);

    return () => {
      active = false;
      clearTimeout(timer);
    };
  }, [query, open]);

  const handleSelect = (href: string) => {
    onOpenChange(false);
    setQuery("");
    router.push(href);
  };

  const categoryIcon = (category: SearchResultItem["category"]) => {
    switch (category) {
      case "Employee":
        return <Users className="h-3.5 w-3.5 text-brand" />;
      case "Request":
        return <FileText className="h-3.5 w-3.5 text-amber-600" />;
      case "Task":
        return <CheckSquare className="h-3.5 w-3.5 text-emerald-600" />;
      default:
        return <Compass className="h-3.5 w-3.5 text-[#64748B]" />;
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-xl gap-0 overflow-hidden p-0">
        <DialogHeader className="sr-only">
          <DialogTitle>Global Search</DialogTitle>
        </DialogHeader>

        <div className="flex items-center gap-2.5 border-b border-[#E5E7EB] px-4 py-3">
          <Search className="h-4 w-4 shrink-0 text-[#94A3B8]" />
          <input
            autoFocus
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search employees, request numbers, tasks, or jump to module..."
            className="w-full bg-transparent text-sm text-[#111827] placeholder:text-[#94A3B8] focus:outline-none"
          />
          {loading && <Loader2 className="h-4 w-4 shrink-0 animate-spin text-[#64748B]" />}
        </div>

        <div className="max-h-[360px] overflow-y-auto p-2">
          {results.length === 0 && !loading ? (
            <div className="px-4 py-8 text-center text-xs text-[#64748B]">
              No matching records or modules found for &ldquo;{query}&rdquo;.
            </div>
          ) : (
            <ul className="space-y-0.5">
              {results.map((item) => (
                <li key={item.id}>
                  <button
                    type="button"
                    onClick={() => handleSelect(item.href)}
                    className="flex w-full items-center justify-between gap-3 rounded-lg px-3 py-2.5 text-left transition-colors hover:bg-[#F8FAFC]"
                  >
                    <div className="flex min-w-0 items-center gap-2.5">
                      <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-[#E5E7EB] bg-white">
                        {categoryIcon(item.category)}
                      </div>
                      <div className="min-w-0">
                        <p className="truncate text-xs font-medium text-[#111827]">{item.title}</p>
                        <p className="truncate text-[11px] text-[#64748B]">{item.subtitle}</p>
                      </div>
                    </div>
                    <div className="flex shrink-0 items-center gap-2">
                      {item.badge && <StatusBadge status={item.badge} showDot={false} />}
                      <ArrowRight className="h-3.5 w-3.5 text-[#94A3B8]" />
                    </div>
                  </button>
                </li>
              ))}
            </ul>
          )}
        </div>

        <div className="flex items-center justify-between border-t border-[#E5E7EB] bg-[#F8FAFC] px-4 py-2 text-[11px] text-[#64748B]">
          <span>Scoped to authorized SMC Cement Group companies</span>
          <span className="font-mono">ESC to close</span>
        </div>
      </DialogContent>
    </Dialog>
  );
}
