import { useEffect, useMemo, useRef, useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { Search, X, ArrowRight } from "lucide-react";

type Entry = {
  title: string;
  bn: string;
  to: string;
  keywords?: string;
};

const ENTRIES: Entry[] = [
  { title: "Home", bn: "হোম", to: "/", keywords: "dashboard ব্যালেন্স" },
  { title: "Send Money", bn: "সেন্ড মানি", to: "/send", keywords: "টাকা পাঠান transfer" },
  { title: "Cash Out", bn: "ক্যাশ আউট", to: "/cash-out", keywords: "withdraw উত্তোলন" },
  { title: "Mobile Recharge", bn: "মোবাইল রিচার্জ", to: "/recharge", keywords: "recharge top up" },
  { title: "Pay Bill", bn: "বিল পরিশোধ", to: "/pay-bill", keywords: "electricity gas bill" },
  { title: "Payment", bn: "পেমেন্ট", to: "/payment", keywords: "merchant qr" },
  { title: "Add Money", bn: "অ্যাড মানি", to: "/add-money", keywords: "deposit ব্যালেন্স" },
  { title: "Request Money", bn: "রিকোয়েস্ট মানি", to: "/request-money" },
  { title: "Statement", bn: "স্টেটমেন্ট", to: "/statement", keywords: "transactions লেনদেন history" },
  { title: "QR Code", bn: "QR কোড", to: "/qr" },
  { title: "Scan QR", bn: "QR স্ক্যান", to: "/scan" },
  { title: "Notifications", bn: "নোটিফিকেশন", to: "/notifications", keywords: "alerts bell" },
  { title: "Live Support", bn: "লাইভ সাপোর্ট", to: "/support", keywords: "chat help" },
  { title: "Account", bn: "অ্যাকাউন্ট", to: "/account", keywords: "profile settings" },
  { title: "More", bn: "আরও", to: "/more" },
  { title: "Inbox", bn: "ইনবক্স", to: "/inbox" },
];

export function GlobalSearch({ open, onClose }: { open: boolean; onClose: () => void }) {
  const [q, setQ] = useState("");
  const navigate = useNavigate();
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (open) setTimeout(() => inputRef.current?.focus(), 50);
    else setQ("");
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  const results = useMemo(() => {
    const term = q.trim().toLowerCase();
    if (!term) return ENTRIES;
    return ENTRIES.filter((e) =>
      [e.title, e.bn, e.keywords ?? "", e.to].join(" ").toLowerCase().includes(term),
    );
  }, [q]);

  if (!open) return null;

  function go(to: string) {
    navigate({ to });
    onClose();
  }

  return (
    <div className="fixed inset-0 z-[80] bg-black/40 backdrop-blur-sm" onClick={onClose}>
      <div
        className="absolute left-1/2 -translate-x-1/2 top-[10vh] w-[92%] max-w-[460px] bg-card rounded-2xl shadow-2xl overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center gap-2 px-3 py-2 border-b">
          <Search className="h-4 w-4 text-muted-foreground" />
          <input
            ref={inputRef}
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="সার্ভিস, পেজ খুঁজুন..."
            className="flex-1 h-10 bg-transparent outline-none text-sm"
          />
          <button onClick={onClose} className="h-8 w-8 rounded-lg grid place-items-center hover:bg-muted">
            <X className="h-4 w-4" />
          </button>
        </div>
        <div className="max-h-[60vh] overflow-y-auto">
          {results.length === 0 && (
            <div className="p-6 text-center text-sm text-muted-foreground">কিছু পাওয়া যায়নি</div>
          )}
          {results.map((r) => (
            <button
              key={r.to + r.title}
              onClick={() => go(r.to)}
              className="w-full flex items-center gap-3 px-4 py-3 hover:bg-muted active:bg-muted text-left"
            >
              <div className="h-9 w-9 rounded-xl bg-primary/10 grid place-items-center">
                <Search className="h-4 w-4 text-primary" />
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-sm font-semibold truncate">{r.bn}</p>
                <p className="text-[11px] text-muted-foreground truncate">{r.title} · {r.to}</p>
              </div>
              <ArrowRight className="h-4 w-4 text-muted-foreground" />
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}
