import { useState, useRef, useMemo } from "react";
import { Link, router } from "@inertiajs/react";
import { route } from "ziggy-js";
import { Search, X, ChevronLeft, ChevronRight, Tag, RotateCcw } from "lucide-react";
import { Seo } from "@/Components/Seo";
import { PromoCard } from "@/Components/PromoCard";
import { PromoDetailModal } from "@/Components/PromoDetailModal";
import { Button } from "@/Components/ui/button";
import { PageHero } from "@/Components/PageHero";
import { useGsapReveal } from "@/hooks/useGsap";
import { withFrontendLayout } from "@/utils/layout";
import type { Paginated, PromoItem } from "@/types";

export interface CategorySection {
    id: number;
    name: string;
    slug: string;
    description?: string | null;
    promos: PromoItem[];
    promos_count: number;
}

export interface CategoryItem {
    id: number;
    name: string;
    slug: string;
    promos_count?: number;
}

interface PromoProps {
    promos: Paginated<PromoItem>;
    categorySections?: CategorySection[];
    categories?: CategoryItem[];
    filters?: { category?: string; q?: string };
    /** Promo dari URL /promo/{slug}: modal detail terbuka otomatis untuk promo ini. */
    promo?: PromoItem | null;
}

function Promo({ promos, categorySections = [], categories = [], filters, promo }: PromoProps) {
    useGsapReveal();

    const [search, setSearch] = useState(filters?.q || "");
    const tabsRef = useRef<HTMLDivElement>(null);

    const activeCategory = filters?.category || "";
    const activeSearch = filters?.q || "";
    const isFiltered = Boolean(activeCategory || activeSearch);

    // Hitung total seluruh promo dari sections atau fallback promos.total
    const totalPromosAll = useMemo(() => {
        if (categorySections.length > 0) {
            return categorySections.reduce((sum, sec) => sum + sec.promos.length, 0);
        }
        return promos.total;
    }, [categorySections, promos.total]);

    // Tab navigasi kategori yang dihasilkan dinamis dari data layanan terdaftar
    const categoryTabs = useMemo(() => {
        return [
            { id: "all", name: "Semua Promo", slug: "", count: totalPromosAll },
            ...categories.map((c) => ({
                id: String(c.id),
                name: c.name,
                slug: c.slug,
                count: c.promos_count,
            })),
        ];
    }, [categories, totalPromosAll]);

    // Fallback sekiranya categorySections kosong tetapi promos.data tersedia
    const fallbackSections: CategorySection[] = useMemo(() => {
        if (categorySections.length > 0) return categorySections;

        if (promos.data.length === 0) return [];

        const grouped = new Map<string, { id: number; name: string; slug: string; promos: PromoItem[] }>();

        promos.data.forEach((p) => {
            const catId = p.category?.id ?? 0;
            const catName = p.category?.name ?? "Penawaran Umum";
            const catSlug = p.category?.slug ?? "umum";

            if (!grouped.has(catSlug)) {
                grouped.set(catSlug, {
                    id: catId,
                    name: catName,
                    slug: catSlug,
                    promos: [],
                });
            }
            grouped.get(catSlug)!.promos.push(p);
        });

        return Array.from(grouped.values()).map((g) => ({
            ...g,
            description: null,
            promos_count: g.promos.length,
        }));
    }, [categorySections, promos.data]);

    // Seksi kategori yang aktif ditampilkan (semua jika 'Semua Promo', atau satu jika ada kategori terpilih)
    const displayedSections = useMemo(() => {
        if (!activeCategory || activeCategory === "all") {
            return fallbackSections;
        }

        if (activeCategory === "promo-terbatas" || activeCategory === "terbatas") {
            return fallbackSections
                .map((sec) => ({
                    ...sec,
                    promos: sec.promos.filter((p) => Boolean(p.end_date)),
                }))
                .filter((sec) => sec.promos.length > 0);
        }

        return fallbackSections.filter((sec) => sec.slug === activeCategory);
    }, [fallbackSections, activeCategory]);

    // Seluruh daftar promo tertera dalam tampilan saat ini untuk navigasi modal
    const allPromos = useMemo(() => {
        return displayedSections.flatMap((s) => s.promos);
    }, [displayedSections]);

    // Modal detail promo dipandu URL: kartu membuka /promo/{slug} dan modal
    // menutup dengan kembali ke /promo, sehingga tombol back browser dan
    // pembagian URL selalu konsisten dengan promo yang tampil.
    const closePromo = () => {
        const params: Record<string, string> = {};
        if (activeCategory) params.category = activeCategory;
        if (activeSearch) params.q = activeSearch;

        router.get(route("promo"), params, {
            preserveScroll: true,
            replace: true,
        });
    };

    const applyFilter = (key: "category" | "q", value?: string) => {
        const params: Record<string, string | undefined> = {
            category: filters?.category || undefined,
            q: filters?.q || undefined,
        };

        if (key === "category") {
            params.category = value || undefined;
        } else if (key === "q") {
            params.q = value || undefined;
        }

        if (!params.category) delete params.category;
        if (!params.q) delete params.q;

        router.get(route("promo"), params, {
            preserveState: true,
            preserveScroll: true,
            replace: true,
        });
    };

    const handleSearchSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        applyFilter("q", search.trim());
    };

    const handleClearSearch = () => {
        setSearch("");
        applyFilter("q", "");
    };

    const handleResetAll = () => {
        setSearch("");
        router.get(route("promo"), {}, {
            preserveState: true,
            preserveScroll: true,
            replace: true,
        });
    };

    const scrollTabs = (direction: "left" | "right") => {
        if (tabsRef.current) {
            const offset = direction === "left" ? -220 : 220;
            const behavior: ScrollBehavior = window.matchMedia("(prefers-reduced-motion: reduce)").matches
                ? "auto"
                : "smooth";
            tabsRef.current.scrollBy({ left: offset, behavior });
        }
    };

    return (
        <>
            <Seo
                title="Promo & Penawaran"
                description="Promo dan penawaran aktif untuk layanan teknologi NDS."
            />

            <PageHero
                title="Promo & Penawaran"
                description="Penawaran aktif untuk layanan dan paket NDS, lengkap dengan ketentuan dan masa berlaku."
            />

            {/* Subbar Navigasi Kategori & Pencarian */}
            <section className="border-b border-border-soft bg-white pt-6 pb-6 sm:pt-8 sm:pb-8">
                <div className="container-nds">
                    <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
                        {/* Kategori Quick Filter Tabs */}
                        <div className="relative flex min-w-0 flex-1 items-center">
                            <button
                                type="button"
                                onClick={() => scrollTabs("left")}
                                className="mr-2 hidden h-11 w-11 shrink-0 cursor-pointer items-center justify-center rounded-xl border border-border-soft bg-white text-navy transition-colors hover:border-navy/40 hover:text-navy focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 lg:flex"
                                aria-label="Geser kategori ke kiri"
                            >
                                <ChevronLeft className="h-4 w-4" />
                            </button>

                            <div
                                ref={tabsRef}
                                role="tablist"
                                aria-label="Kategori promo"
                                className="no-scrollbar flex w-full items-center gap-2 overflow-x-auto px-0.5 py-1 scroll-smooth"
                            >
                                {categoryTabs.map((cat) => {
                                    const isActive = cat.slug === "" ? !activeCategory : activeCategory === cat.slug;

                                    return (
                                        <button
                                            key={cat.id}
                                            type="button"
                                            role="tab"
                                            aria-selected={isActive}
                                            onClick={() => applyFilter("category", cat.slug)}
                                            className={`inline-flex h-11 shrink-0 cursor-pointer items-center gap-2 rounded-xl border px-4 text-xs font-bold transition-all duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 ${
                                                isActive
                                                    ? "border-navy bg-navy text-white shadow-xs"
                                                    : "border-border-soft bg-white text-navy hover:border-navy/40 hover:bg-slate-50/60"
                                            }`}
                                        >
                                            <span>{cat.name}</span>
                                            {typeof cat.count === "number" && cat.count > 0 && (
                                                <span
                                                    className={`inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold tracking-wide ${
                                                        isActive
                                                            ? "bg-white/20 text-white"
                                                            : "bg-slate-100 text-slate-600"
                                                    }`}
                                                >
                                                    {cat.count}
                                                </span>
                                            )}
                                        </button>
                                    );
                                })}
                            </div>

                            <button
                                type="button"
                                onClick={() => scrollTabs("right")}
                                className="ml-2 hidden h-11 w-11 shrink-0 cursor-pointer items-center justify-center rounded-xl border border-border-soft bg-white text-navy transition-colors hover:border-navy/40 hover:text-navy focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 lg:flex"
                                aria-label="Geser kategori ke kanan"
                            >
                                <ChevronRight className="h-4 w-4" />
                            </button>
                        </div>

                        {/* Search Input Form */}
                        <form onSubmit={handleSearchSubmit} className="relative w-full shrink-0 lg:w-72 xl:w-80">
                            <Search className="pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-body-text" />
                            <input
                                type="search"
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                placeholder="Cari promo..."
                                className="h-11 w-full rounded-xl border border-border-soft bg-white pl-10 pr-11 text-sm text-navy placeholder:text-body-text focus:border-navy focus:outline-none focus:ring-2 focus:ring-navy/20"
                                aria-label="Cari promo"
                            />
                            {search && (
                                <button
                                    type="button"
                                    onClick={handleClearSearch}
                                    className="absolute right-1 top-1/2 flex h-11 w-11 -translate-y-1/2 cursor-pointer items-center justify-center rounded-xl text-body-text transition-colors hover:text-navy focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2"
                                    aria-label="Hapus kata kunci pencarian"
                                >
                                    <X className="h-3.5 w-3.5" />
                                </button>
                            )}
                        </form>
                    </div>

                    {/* Filter Aktif Bar */}
                    {isFiltered && (
                        <div className="mt-4 flex flex-wrap items-center justify-between gap-3 border-t border-border-soft pt-4 text-xs text-body-text">
                            <div className="flex flex-wrap items-center gap-2">
                                <span className="font-medium text-slate-500">Filter aktif:</span>
                                {activeCategory && (
                                    <span className="inline-flex items-center gap-1.5 rounded-lg border border-border-soft bg-slate-50 px-2.5 py-1 font-semibold text-navy">
                                        Kategori:{" "}
                                        {categoryTabs.find((c) => c.slug === activeCategory)?.name || activeCategory}
                                        <button
                                            type="button"
                                            onClick={() => applyFilter("category", "")}
                                            className="-my-1 -mr-1 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-md text-slate-500 transition-colors hover:bg-slate-200 hover:text-navy focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
                                            aria-label="Hapus filter kategori"
                                        >
                                            <X className="h-3 w-3" />
                                        </button>
                                    </span>
                                )}
                                {activeSearch && (
                                    <span className="inline-flex items-center gap-1.5 rounded-lg border border-border-soft bg-slate-50 px-2.5 py-1 font-semibold text-navy">
                                        Cari: "{activeSearch}"
                                        <button
                                            type="button"
                                            onClick={handleClearSearch}
                                            className="-my-1 -mr-1 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-md text-slate-500 transition-colors hover:bg-slate-200 hover:text-navy focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
                                            aria-label="Hapus filter pencarian"
                                        >
                                            <X className="h-3 w-3" />
                                        </button>
                                    </span>
                                )}
                                <span className="ml-1 text-slate-500">
                                    ({allPromos.length} penawaran ditampilkan)
                                </span>
                            </div>
                            <button
                                type="button"
                                onClick={handleResetAll}
                                className="inline-flex min-h-8 cursor-pointer items-center gap-1.5 font-semibold text-navy underline underline-offset-4 transition-colors hover:text-tech-blue focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
                            >
                                <RotateCcw className="h-3 w-3" />
                                Reset Semua Filter
                            </button>
                        </div>
                    )}
                </div>
            </section>

            {/* Konten Katalog Terstruktur per Kategori Layanan */}
            <main className="bg-white pb-16 sm:pb-20 lg:pb-24">
                <div className="container-nds">
                    {displayedSections.length === 0 || allPromos.length === 0 ? (
                        <div className="mx-auto my-16 max-w-lg rounded-2xl border border-border-soft bg-white p-8 text-center sm:my-20 sm:p-12">
                            <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full border border-tech-blue/30 text-tech-blue">
                                <Tag className="h-6 w-6" aria-hidden="true" />
                            </div>
                            <h2 className="mt-5 text-lg font-bold text-navy sm:text-xl">Tidak ada promo ditemukan</h2>
                            <p className="mt-2 text-sm leading-relaxed text-body-text">
                                {isFiltered
                                    ? "Tidak ada penawaran aktif yang cocok dengan filter atau kata kunci saat ini. Coba kata kunci lain atau reset filter."
                                    : "Belum ada promo aktif untuk kategori ini. Hubungi tim kami untuk konsultasi penawaran khusus."}
                            </p>
                            <div className="mt-6 flex flex-wrap items-center justify-center gap-3">
                                {isFiltered && (
                                    <Button type="button" variant="secondary" onClick={handleResetAll}>
                                        Lihat Semua Promo
                                    </Button>
                                )}
                                <Button asChild variant="primary">
                                    <Link href={route("contact")}>
                                        <span>Konsultasi Penawaran</span>
                                    </Link>
                                </Button>
                            </div>
                        </div>
                    ) : (
                        <div className="divide-y divide-border-soft/60">
                            {displayedSections.map((section) => (
                                <section
                                    key={section.id || section.slug}
                                    id={`category-${section.slug}`}
                                    className="py-8 sm:py-10 first:pt-8 last:pb-4"
                                >
                                    {/* Category Section Header */}
                                    <div className="flex flex-col gap-1.5 sm:flex-row sm:items-baseline sm:justify-between">
                                        <div>
                                            <div className="flex flex-wrap items-center gap-2.5">
                                                <h2 className="text-xl font-bold tracking-[-0.02em] text-navy sm:text-2xl">
                                                    {section.name}
                                                </h2>
                                                <span className="inline-flex items-center rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-semibold text-slate-700">
                                                    {section.promos.length} Penawaran
                                                </span>
                                            </div>
                                            {section.description && (
                                                <p className="mt-1.5 max-w-2xl text-sm leading-relaxed text-body-text">
                                                    {section.description}
                                                </p>
                                            )}
                                        </div>

                                        {activeCategory && (
                                            <button
                                                type="button"
                                                onClick={handleResetAll}
                                                className="inline-flex items-center gap-1.5 text-xs font-semibold text-navy transition-colors hover:text-tech-blue"
                                            >
                                                <ChevronLeft className="h-3.5 w-3.5" />
                                                Lihat Semua Kategori
                                            </button>
                                        )}
                                    </div>

                                    {/* Grid katalog padat: 2 kolom di ponsel, 2 di tablet,
                                        3 di laptop, 4 di desktop lebar. */}
                                    <div className="mt-4 grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-3 lg:gap-5 xl:grid-cols-4">
                                        {section.promos.map((item) => (
                                            <PromoCard key={item.id} promo={item} variant="light" />
                                        ))}
                                    </div>
                                </section>
                            ))}
                        </div>
                    )}
                </div>
            </main>

            {/* Modal Detail Promo Terpadu */}
            <PromoDetailModal promo={promo ?? null} onClose={closePromo} related={allPromos} />
        </>
    );
}

export default withFrontendLayout(Promo);
