import BildirimDropdown from '@/Components/BildirimDropdown';
import GenelArama from '@/Components/GenelArama';
import { useGorevModal } from '@/Components/GorevModalProvider';
import { useProjeModal } from '@/Components/ProjeModalProvider';
import IdleTimeout from '@/Components/IdleTimeout';
import { useModulModal, urlToModul } from '@/Components/ModulModalProvider';
import ToasterContainer from '@/Components/Toaster';
import { yolNormalize } from '@/lib/url';
import { useYetki } from '@/lib/yetki';
import Link from '@/Components/Link';
import { router, usePage } from '@inertiajs/react';
import { PropsWithChildren, ReactNode, useState } from 'react';
import {
    Activity,
    ArrowLeftRight,
    BarChart3,
    Briefcase,
    Building2,
    Calculator,
    CalendarClock,
    ChevronDown,
    ChevronsUpDown,
    Coins,
    Contact,
    FileSignature,
    FolderOpen,
    LayoutDashboard,
    ListChecks,
    ListPlus,
    LogOut,
    Menu,
    Package,
    Plus,
    Settings,
    ShieldCheck,
    Tags,
    UserCircle2,
    UserCog,
    Users,
    Wallet,
    X,
} from 'lucide-react';

interface ManifestSidebarItem {
    baslik: string;
    href: string;
    icon: string;
    yetki?: string;
    ekle_href?: string;
    ekle_yetki?: string;
    /** Active state için ek path prefix (örn: href=/projeler/board, match_prefix=/projeler) */
    match_prefix?: string;
}

// Modül manifest'inden gelen string ikon adlarını lucide componentlarına çevir
const IKON_MAP: Record<string, typeof LayoutDashboard> = {
    Activity, ArrowLeftRight, BarChart3, Briefcase, Building2, Calculator, CalendarClock, Coins, Contact,
    FileSignature, FolderOpen, LayoutDashboard, ListChecks, ListPlus, Package, Settings, ShieldCheck, Tags, UserCircle2, UserCog, Users, Wallet,
};

type AppLayoutProps = PropsWithChildren<{ title?: string; actions?: ReactNode; actionsNowrap?: boolean }>;

export default function AppLayout(props: AppLayoutProps) {
    // ModulModalProvider artık app.tsx'te kök seviyede sarıyor — burada duplikasyon yok.
    return <AppLayoutInner {...props} />;
}

function AppLayoutInner({
    children,
    title,
    actions,
    actionsNowrap,
}: AppLayoutProps) {
    const { auth, firmalar, aktif_firma, aktif_moduller, modul_manifest, sistem_markalama } = usePage().props as any;
    const markalama = sistem_markalama as { ad?: string; kisa_ad?: string; slogan?: string; logo_url?: string | null } | undefined;
    const user = auth?.user;
    const { can } = useYetki();
    const gorevModal = useGorevModal();
    const projeModal = useProjeModal();
    const modulModal = useModulModal();
    const aktifModulSet = new Set((aktif_moduller as string[] | undefined) ?? []);
    const gorevOlustursunMu = aktifModulSet.has('gorev') && can('gorev.ekle');

    const [sidebarOpen, setSidebarOpen] = useState(false);
    const [profileOpen, setProfileOpen] = useState(false);
    const [firmaOpen, setFirmaOpen] = useState(false);

    // Sondaki "/" karşılaştırmayı bozmasın: "/musteriler/" ile "/musteriler" aynı sayılır.
    const currentPath = yolNormalize(typeof window !== 'undefined' ? window.location.pathname : '/');
    const isActiveItem = (item: ManifestSidebarItem) => {
        const href = yolNormalize(item.href);
        if (currentPath === href) return true;
        if (currentPath.startsWith(href + '/')) return true;
        const prefix = item.match_prefix ? yolNormalize(item.match_prefix) : null;
        if (prefix && (currentPath === prefix || currentPath.startsWith(prefix + '/'))) return true;
        return false;
    };

    // Modül manifest'inden aktif modüllerin sidebar item'larını üret (yetki + ikon filtreli)
    const moduller = (aktif_moduller as string[] | undefined) ?? [];
    const manifest = (modul_manifest as Record<string, { ad: string; sidebar: ManifestSidebarItem[] }> | undefined) ?? {};
    type ModulSidebar = { kod: string; ad: string; items: ManifestSidebarItem[] };
    const sidebarModuller: ModulSidebar[] = moduller
        .map((kod) => {
            const m = manifest[kod];
            if (!m) return null;
            const items = (m.sidebar || []).filter((i) => !i.yetki || can(i.yetki));
            if (items.length === 0) return null;
            return { kod, ad: m.ad, items };
        })
        .filter(Boolean) as ModulSidebar[];


    const firmaSec = (id: number) => {
        router.post(`/firma-aktif/${id}/`, {}, { preserveScroll: true });
        setFirmaOpen(false);
    };

    return (
        <div className="min-h-screen bg-slate-50">
            <ToasterContainer />
            <IdleTimeout />
            {sidebarOpen && (
                <div className="fixed inset-0 z-40 bg-slate-900/50 lg:hidden" onClick={() => setSidebarOpen(false)} />
            )}

            <aside className={`fixed inset-y-0 left-0 z-50 flex w-64 transform flex-col bg-slate-900 text-slate-100 transition-transform duration-200 lg:translate-x-0 ${sidebarOpen ? 'translate-x-0' : '-translate-x-full'}`}>
                <div className="flex h-16 flex-shrink-0 items-center justify-between border-b border-slate-800 px-6">
                    <div className="flex min-w-0 items-center gap-2">
                        {markalama?.logo_url ? (
                            <img src={markalama.logo_url} alt="Logo" className="h-9 w-9 flex-shrink-0 rounded-lg object-contain bg-white p-0.5" />
                        ) : (
                            <div className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-lg bg-blue-600">
                                <Wallet className="h-5 w-5 text-white" />
                            </div>
                        )}
                        <div className="min-w-0">
                            <div className="truncate text-sm font-bold">{markalama?.kisa_ad ?? 'Cari Takip'}</div>
                            <div className="truncate text-xs text-slate-400">{markalama?.slogan ?? 'Muhasebe Sistemi'}</div>
                        </div>
                    </div>
                    <button className="lg:hidden" onClick={() => setSidebarOpen(false)}><X className="h-5 w-5" /></button>
                </div>

                <nav className="flex-1 overflow-y-auto p-3">
                    {/* Ana sayfa — her zaman görünür */}
                    <div className="space-y-1">
                        <Link href="/"
                            className={`flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition ${currentPath === '/' ? 'bg-blue-600 text-white' : 'text-slate-300 hover:bg-slate-800 hover:text-white'}`}
                        >
                            <LayoutDashboard className="h-5 w-5" />
                            Ana Sayfa
                        </Link>
                    </div>

                    {/* Modül bazlı gruplar */}
                    {sidebarModuller.map((modul) => (
                        <div key={modul.kod}>
                            <div className="mt-5 px-3 text-xs font-semibold uppercase tracking-wider text-slate-500">
                                {modul.ad}
                            </div>
                            <div className="mt-2 space-y-1">
                                {modul.items.map((item) => {
                                    const Icon = IKON_MAP[item.icon] ?? LayoutDashboard;
                                    const active = isActiveItem(item);
                                    const ekleGoster = !!item.ekle_href && (!item.ekle_yetki || can(item.ekle_yetki));
                                    // Görev için + butonu modal açar, navigasyon yapmaz
                                    const isGorev = item.href.startsWith('/gorevler') || (item.ekle_href ?? '').startsWith('/gorevler');
                                    const isProje = item.href.startsWith('/projeler') || (item.ekle_href ?? '').startsWith('/projeler');
                                    const ekleButonClass = `flex w-9 items-center justify-center rounded-lg transition ${active ? 'bg-blue-700 text-white hover:bg-blue-800' : 'bg-slate-800/60 text-slate-400 hover:bg-emerald-600 hover:text-white'}`;
                                    const ekleTitle = `Yeni ${item.baslik.replace(/ler$|lar$/, '')} ekle`;
                                    return (
                                        <div key={item.href} className="flex items-stretch gap-1">
                                            <Link href={item.href}
                                                className={`flex flex-1 items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition ${active ? 'bg-blue-600 text-white' : 'text-slate-300 hover:bg-slate-800 hover:text-white'}`}
                                            >
                                                <Icon className="h-5 w-5" />
                                                {item.baslik}
                                            </Link>
                                            {ekleGoster && isGorev && (
                                                <button type="button"
                                                    onClick={() => gorevModal.yeniGorev()}
                                                    title={ekleTitle}
                                                    className={ekleButonClass}
                                                >
                                                    <Plus className="h-4 w-4" />
                                                </button>
                                            )}
                                            {ekleGoster && !isGorev && isProje && (
                                                <button type="button"
                                                    onClick={() => projeModal.yeniProje()}
                                                    title={ekleTitle}
                                                    className={ekleButonClass}
                                                >
                                                    <Plus className="h-4 w-4" />
                                                </button>
                                            )}
                                            {ekleGoster && !isGorev && !isProje && (() => {
                                                const modulAdi = urlToModul(item.ekle_href!);
                                                if (modulAdi) {
                                                    return (
                                                        <button
                                                            type="button"
                                                            onClick={() => {
                                                                modulModal.ac(modulAdi, 'yeni');
                                                                setSidebarOpen(false);
                                                            }}
                                                            title={ekleTitle}
                                                            className={ekleButonClass}
                                                        >
                                                            <Plus className="h-4 w-4" />
                                                        </button>
                                                    );
                                                }
                                                return (
                                                    <Link
                                                        href={item.ekle_href!}
                                                        title={ekleTitle}
                                                        className={ekleButonClass}
                                                    >
                                                        <Plus className="h-4 w-4" />
                                                    </Link>
                                                );
                                            })()}
                                        </div>
                                    );
                                })}
                            </div>
                        </div>
                    ))}
                </nav>
            </aside>

            <div className="lg:pl-64">
                <header className="sticky top-0 z-30 flex h-16 items-center justify-between bg-white px-4 sm:px-6 border-b">
                    <div className="flex items-center gap-3">
                        <button className="rounded-lg text-slate-600 hover:bg-slate-100 lg:hidden" onClick={() => setSidebarOpen(true)}>
                            <Menu className="h-5 w-5" />
                        </button>
                        {title && <h1 className="truncate text-sm font-semibold text-slate-900 sm:text-lg">{title}</h1>}
                    </div>

                    <div className="flex items-center gap-2">
                        {/* Genel arama (Ctrl+K) */}
                        <GenelArama />

                        {/* Global hızlı görev oluştur */}
                        {gorevOlustursunMu && (
                            <button onClick={() => gorevModal.yeniGorev()}
                                title="Hızlı görev oluştur"
                                className="inline-flex h-9 items-center gap-1.5 rounded-lg bg-blue-600 px-3 text-sm font-semibold text-white shadow-sm transition hover:bg-blue-700">
                                <Plus className="h-4 w-4" />
                                <span className="hidden sm:inline">Görev</span>
                            </button>
                        )}

                        {/* Bildirim çanı */}
                        {user && <BildirimDropdown />}

                        {/* Firma seçici */}
                        {firmalar && firmalar.length > 0 && (
                            <div className="relative">
                                <button onClick={() => setFirmaOpen(!firmaOpen)}
                                    className="inline-flex h-9 items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 text-sm hover:bg-slate-50"
                                >
                                    <Building2 className="h-4 w-4 text-slate-500" />
                                    <span className="hidden max-w-[140px] truncate font-medium text-slate-700 sm:inline">{aktif_firma?.ad ?? 'Firma seçin'}</span>
                                    <ChevronsUpDown className="h-3.5 w-3.5 text-slate-400" />
                                </button>
                                {firmaOpen && (
                                    <div className="absolute right-0 z-50 mt-2 w-64 max-w-[calc(100vw-2rem)] rounded-lg border border-slate-200 bg-white py-1 shadow-lg">
                                        <div className="px-3 py-2 text-xs font-semibold uppercase text-slate-500">Aktif Firma</div>
                                        {firmalar.map((f: any) => (
                                            <button key={f.id} onClick={() => firmaSec(f.id)}
                                                className={`flex w-full items-center justify-between px-3 py-2 text-left text-sm hover:bg-slate-50 ${aktif_firma?.id === f.id ? 'bg-blue-50 text-blue-700 font-medium' : 'text-slate-700'}`}
                                            >
                                                {f.ad}
                                                {aktif_firma?.id === f.id && <span className="text-xs">●</span>}
                                            </button>
                                        ))}
                                        {can('firma.goruntule') && (
                                            <Link href="/firmalar/" className="block border-t border-slate-100 px-3 py-2 text-xs font-medium text-blue-600 hover:bg-blue-50">
                                                Firmaları yönet →
                                            </Link>
                                        )}
                                    </div>
                                )}
                            </div>
                        )}

                        {/* Profil */}
                        <div className="relative">
                            <button onClick={() => setProfileOpen(!profileOpen)}
                                className="inline-flex h-9 items-center gap-2 rounded-lg border border-slate-200 bg-white px-2 hover:bg-slate-50"
                            >
                                {user?.avatar_url_full ? (
                                    <img src={user.avatar_url_full} alt={user.name}
                                        className="h-6 w-6 rounded-full object-cover ring-1 ring-slate-200" />
                                ) : (
                                    <div className="flex h-6 w-6 items-center justify-center rounded-full bg-blue-600 text-xs font-semibold text-white">
                                        {user?.name?.charAt(0).toUpperCase() ?? 'U'}
                                    </div>
                                )}
                                <span className="hidden max-w-[120px] truncate text-sm font-medium text-slate-700 sm:block">{user?.name}</span>
                                <ChevronDown className="h-4 w-4 text-slate-500" />
                            </button>
                            {profileOpen && (
                                <div className="absolute right-0 z-50 mt-2 w-56 max-w-[calc(100vw-2rem)] rounded-lg border border-slate-200 bg-white py-1 shadow-lg">
                                    <div className="border-b border-slate-100 px-4 py-2">
                                        <div className="text-sm font-medium text-slate-900">{user?.name}</div>
                                        <div className="text-xs text-slate-500">{user?.email}</div>
                                        {user?.is_admin && (
                                            <div className="mt-1 inline-flex items-center gap-1 rounded-full bg-amber-50 px-2 py-0.5 text-xs font-medium text-amber-700">
                                                <ShieldCheck className="h-3 w-3" /> Sistem Admin
                                            </div>
                                        )}
                                    </div>
                                    <Link href={route('profile.edit')} className="block px-4 py-2 text-sm text-slate-700 hover:bg-slate-100">
                                        Profil Ayarları
                                    </Link>
                                    <button onClick={() => router.post(route('logout'))}
                                        className="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-red-600 hover:bg-red-50"
                                    >
                                        <LogOut className="h-4 w-4" />
                                        Çıkış Yap
                                    </button>
                                </div>
                            )}
                        </div>
                    </div>
                </header>

                {actions && (
                    <div className="border-b border-slate-200 bg-white px-4 py-3 sm:px-6">
                        <div className={`flex items-center justify-between gap-2 ${actionsNowrap ? 'flex-nowrap overflow-x-auto' : 'flex-wrap'}`}>{actions}</div>
                    </div>
                )}

                {/* Flash mesajları artık sağ üst köşede toast olarak görünür (ToasterContainer) */}

                <main className="p-4 sm:p-6">{children}</main>
            </div>
        </div>
    );
}
