import { ModulAdi, useModulModal } from '@/Components/ModulModalProvider';
import { useProjeModal } from '@/Components/ProjeModalProvider';
import { Dialog, DialogPanel, Transition, TransitionChild } from '@headlessui/react';
import { router } from '@inertiajs/react';
import {
    Activity, ArrowLeftRight, ArrowRight, Bell, Briefcase, Building2, CalendarClock, Coins, Contact,
    FileSignature, FileText, FolderOpen, ListChecks, LucideIcon, Package, PackageOpen, Paperclip, Search,
    UserCircle2, UserCog, Users, Wallet, Wrench, X,
} from 'lucide-react';
import { Fragment, useEffect, useRef, useState } from 'react';

interface Sonuc {
    id: number;
    baslik: string;
    aciklama: string;
    hedef_modul?: string | null;
    hedef_id?: number;
    hedef_url?: string | null;
}

interface Grup {
    modul: ModulAdi | 'proje' | 'gorev' | 'randevu' | 'teklif' | 'servis' | 'belge' | 'kullanici' | 'firma' | 'bildirim' | 'log' | 'para-birimi';
    baslik: string;
    icon: string;
    toplam: number;
    liste_url: string;
    items: Sonuc[];
}

const IKON_MAP: Record<string, LucideIcon> = {
    Users, Contact, Package, PackageOpen, UserCircle2, Wallet, ArrowLeftRight, Briefcase,
    ListChecks, CalendarClock, FileText, FileSignature, FolderOpen, Wrench, Paperclip, UserCog, Building2,
    Bell, Activity, Coins,
};

export default function GenelArama() {
    const [acik, setAcik] = useState(false);
    const [q, setQ] = useState('');
    const [yukleniyor, setYukleniyor] = useState(false);
    const [gruplar, setGruplar] = useState<Grup[]>([]);
    const modulModal = useModulModal();
    const projeModal = useProjeModal();
    const inputRef = useRef<HTMLInputElement>(null);

    // Klavye kısayolu: Ctrl/Cmd + K
    useEffect(() => {
        const handler = (e: KeyboardEvent) => {
            if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') {
                e.preventDefault();
                setAcik(true);
            }
            if (e.key === 'Escape' && acik) {
                setAcik(false);
            }
        };
        window.addEventListener('keydown', handler);
        return () => window.removeEventListener('keydown', handler);
    }, [acik]);

    // Debounced canli arama
    useEffect(() => {
        if (!acik) return;
        if (q.trim().length < 2) {
            setGruplar([]);
            return;
        }
        const ctrl = new AbortController();
        const timer = setTimeout(() => {
            setYukleniyor(true);
            fetch(`/api/ara/genel?q=${encodeURIComponent(q.trim())}`, {
                signal: ctrl.signal,
                headers: { Accept: 'application/json' },
                credentials: 'same-origin',
            })
                .then((r) => r.json())
                .then((d: { gruplar: Grup[] }) => setGruplar(d.gruplar ?? []))
                .catch((e) => { if (e.name !== 'AbortError') setGruplar([]); })
                .finally(() => setYukleniyor(false));
        }, 250);
        return () => { clearTimeout(timer); ctrl.abort(); };
    }, [q, acik]);

    const ac = () => { setAcik(true); setTimeout(() => inputRef.current?.focus(), 50); };
    const kapat = () => { setAcik(false); setQ(''); setGruplar([]); };

    const itemAc = (modul: string, id: number, item?: Sonuc) => {
        kapat();
        if (['cari', 'musteri', 'urun', 'personel', 'kasa', 'hareket', 'teklif', 'servis', 'firma'].includes(modul)) {
            modulModal.ac(modul as ModulAdi, id);
        } else if (modul === 'proje') {
            projeModal.projeDuzenle(id);
        } else if (modul === 'gorev') {
            router.visit(`/gorevler/?gorev=${id}`);
        } else if (modul === 'randevu') {
            router.visit(`/randevular/?randevu=${id}`);
        } else if (modul === 'belge' && item?.hedef_modul && item.hedef_id) {
            // Belge hangi modüle aitse o modülün modalını aç
            if (['musteri', 'personel', 'teklif', 'servis'].includes(item.hedef_modul)) {
                modulModal.ac(item.hedef_modul as ModulAdi, item.hedef_id);
            } else if (item.hedef_modul === 'proje') {
                projeModal.projeDuzenle(item.hedef_id);
            } else if (item.hedef_modul === 'gorev') {
                router.visit(`/gorevler/?gorev=${item.hedef_id}`);
            } else if (item.hedef_modul === 'randevu') {
                router.visit(`/randevular/?randevu=${item.hedef_id}`);
            }
        } else if (modul === 'kullanici') {
            router.visit(`/kullanicilar/?arama=${id}`);
        } else if (modul === 'bildirim' && item?.hedef_url) {
            router.visit(item.hedef_url);
        } else if (modul === 'log') {
            router.visit('/gunluk-kayitlar/');
        } else if (modul === 'para-birimi') {
            router.visit('/para-birimleri/');
        }
    };

    const tumunuGoster = (url: string) => { kapat(); router.visit(url); };

    return (
        <>
            <button
                type="button"
                onClick={ac}
                className="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-slate-200 bg-white text-blue-600 transition hover:bg-blue-50"
                title="Genel ara (Ctrl+K)"
            >
                <Search className="h-4 w-4" />
            </button>

            <Transition show={acik} as={Fragment}>
                <Dialog onClose={kapat} className="fixed inset-0 z-[100] flex items-start justify-center overflow-y-auto p-2 pt-2 sm:p-[10px] sm:pt-[10vh]">
                    <TransitionChild
                        as={Fragment}
                        enter="ease-out duration-200" enterFrom="opacity-0" enterTo="opacity-100"
                        leave="ease-in duration-150" leaveFrom="opacity-100" leaveTo="opacity-0"
                    >
                        <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm" aria-hidden="true" />
                    </TransitionChild>

                    <TransitionChild
                        as={Fragment}
                        enter="ease-out duration-200"
                        enterFrom="opacity-0 scale-95 translate-y-2"
                        enterTo="opacity-100 scale-100 translate-y-0"
                        leave="ease-in duration-150"
                        leaveFrom="opacity-100 scale-100"
                        leaveTo="opacity-0 scale-95"
                    >
                        <DialogPanel className="relative z-10 w-full max-w-2xl overflow-hidden rounded-2xl bg-white shadow-2xl ring-1 ring-black/5">
                            <div className="flex items-center gap-3 border-b border-slate-200 px-4 py-3">
                                <Search className="h-5 w-5 text-slate-400" />
                                <input
                                    ref={inputRef}
                                    type="text"
                                    autoFocus
                                    value={q}
                                    onChange={(e) => setQ(e.target.value)}
                                    placeholder="Aranacak içerik..."
                                    className="flex-1 border-0 bg-transparent text-base text-slate-900 placeholder-slate-400 focus:outline-none focus:ring-0"
                                />
                                {q && (
                                    <button onClick={() => setQ('')} className="rounded p-1 text-slate-400 hover:bg-slate-100 hover:text-slate-700">
                                        <X className="h-4 w-4" />
                                    </button>
                                )}
                                <button onClick={kapat} className="hidden md:inline rounded border border-slate-200 bg-slate-50 px-1.5 py-0.5 text-[10px] font-mono text-slate-500">
                                    ESC
                                </button>
                            </div>

                            <div className="max-h-[60vh] overflow-y-auto">
                                {q.trim().length < 2 && (
                                    <div className="px-4 py-8 text-center text-sm text-slate-500">
                                        En az 2 karakter yazın...
                                    </div>
                                )}
                                {q.trim().length >= 2 && yukleniyor && gruplar.length === 0 && (
                                    <div className="px-4 py-8 text-center text-sm text-slate-500">
                                        Aranıyor...
                                    </div>
                                )}
                                {q.trim().length >= 2 && !yukleniyor && gruplar.length === 0 && (
                                    <div className="px-4 py-8 text-center text-sm text-slate-500">
                                        Sonuç bulunamadı.
                                    </div>
                                )}
                                {gruplar.map((grup) => {
                                    const Icon = IKON_MAP[grup.icon] ?? Search;
                                    return (
                                        <div key={grup.modul} className="border-b border-slate-100 last:border-b-0">
                                            <div className="flex items-center justify-between bg-slate-50 px-4 py-2">
                                                <div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-slate-700">
                                                    <Icon className="h-4 w-4 text-slate-500" />
                                                    {grup.baslik}
                                                    <span className="rounded-full bg-white px-2 py-0.5 text-[10px] font-semibold text-slate-600 shadow-sm">
                                                        {grup.toplam}
                                                    </span>
                                                </div>
                                                {grup.toplam > grup.items.length && grup.liste_url && grup.liste_url !== '#' && (
                                                    <button
                                                        type="button"
                                                        onClick={() => tumunuGoster(grup.liste_url)}
                                                        className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-[11px] font-medium text-blue-600 hover:bg-blue-50"
                                                    >
                                                        Tümünü göster ({grup.toplam}) <ArrowRight className="h-3 w-3" />
                                                    </button>
                                                )}
                                            </div>
                                            <ul className="divide-y divide-slate-100">
                                                {grup.items.map((it) => (
                                                    <li key={`${grup.modul}-${it.id}`}>
                                                        <button
                                                            type="button"
                                                            onClick={() => itemAc(grup.modul, it.id, it)}
                                                            className="flex w-full items-center gap-3 px-4 py-2.5 text-left text-sm transition hover:bg-blue-50"
                                                        >
                                                            <div className="min-w-0 flex-1">
                                                                <div className="truncate font-medium text-slate-900">{it.baslik}</div>
                                                                {it.aciklama && (
                                                                    <div className="truncate text-xs text-slate-500">{it.aciklama}</div>
                                                                )}
                                                            </div>
                                                            <ArrowRight className="h-3.5 w-3.5 flex-shrink-0 text-slate-300" />
                                                        </button>
                                                    </li>
                                                ))}
                                            </ul>
                                        </div>
                                    );
                                })}
                            </div>

                            {gruplar.length > 0 && (
                                <div className="border-t border-slate-200 bg-slate-50 px-4 py-2 text-[11px] text-slate-500">
                                    <strong>{gruplar.reduce((t, g) => t + g.items.length, 0)}</strong> sonuç gösteriliyor · Toplam <strong>{gruplar.reduce((t, g) => t + g.toplam, 0)}</strong>
                                </div>
                            )}
                        </DialogPanel>
                    </TransitionChild>
                </Dialog>
            </Transition>
        </>
    );
}
