import { Link, router } from "@inertiajs/react";
import { route } from "ziggy-js";
import { ArrowRight, Search } from "lucide-react";
import { Seo } from "@/Components/Seo";
import { ServiceCard } from "@/Components/ServiceCard";
import { SectionHeading } from "@/Components/SectionHeading";
import { Button } from "@/Components/ui/button";
import { CenteredCardCarousel } from "@/Components/ui/CenteredCardCarousel";
import { useGsapReveal, useHeroAnimation } from "@/hooks/useGsap";
import { withFrontendLayout } from "@/utils/layout";
import type { ServiceItem, CompanySettings, Paginated } from "@/types";
import { useEffect, useRef, useState } from "react";

interface Props {
    services: Paginated<ServiceItem>;
    filters?: { q?: string };
    settings?: CompanySettings;
}

function ServicesIndex({ services, filters }: Props) {
    useHeroAnimation();
    useGsapReveal();

    const [search, setSearch] = useState(filters?.q ?? "");
    const isFirstRender = useRef(true);

    // Pencarian dijalankan di server supaya mencakup seluruh halaman,
    // bukan hanya kartu yang sedang tampil.
    useEffect(() => {
        if (isFirstRender.current) {
            isFirstRender.current = false;
            return;
        }

        const timer = setTimeout(() => {
            router.get(
                route("services.index"),
                search ? { q: search } : {},
                { preserveState: true, preserveScroll: true, replace: true },
            );
        }, 350);

        return () => clearTimeout(timer);
    }, [search]);

    const filteredServices = services.data;

    return (
        <>
            <Seo
                title="Semua Layanan"
                description="Jelajahi semua layanan teknologi kami: Web Development, Software Application, Management Network, IT Consultant, Server Management, dan CCTV."
            />

            {/* Hero Section */}
            <section className="relative overflow-hidden bg-navy pt-24 pb-12 sm:pt-28 lg:pt-28 lg:pb-16 xl:pt-32 xl:pb-20">
                <div className="absolute inset-0 bg-gradient-to-r from-deep-navy via-navy/85 to-navy/50" />
                <div className="container-nds relative z-10">
                    <div className="max-w-2xl">
                        <h1 className="heading-1 text-white">
                            Solusi Teknologi Terintegrasi untuk Bisnis Anda
                        </h1>
                        <p className="mt-4 text-base leading-relaxed text-white/80 sm:text-lg">
                            Kami menyediakan layanan teknologi dari pengembangan website hingga infrastruktur jaringan dan keamanan. Temukan solusi yang tepat untuk kebutuhan bisnis Anda.
                        </p>
                    </div>
                </div>
            </section>

            {/* Search & Filter */}
            <section className="bg-off-white py-8 border-b border-border-soft">
                <div className="container-nds">
                    <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                        <div className="relative flex-1 max-w-md">
                            <Search className="pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 text-body-text/60" />
                            <input
                                type="text"
                                placeholder="Cari layanan..."
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                className="input pl-10 w-full"
                            />
                        </div>
                        <p className="text-sm text-body-text" aria-live="polite">
                            {filteredServices.length} layanan
                            {search && <> untuk pencarian &ldquo;{search}&rdquo;</>}
                        </p>
                    </div>
                </div>
            </section>

            {/* Services Grid */}
            <section className="bg-off-white py-12 lg:py-16 xl:py-20">
                <div className="container-nds">
                    <SectionHeading
                        title="Layanan kami"
                        description="Solusi teknologi terintegrasi untuk mendukung pertumbuhan bisnis Anda."
                    />

                    <div className="mt-10">
                        {filteredServices.length > 0 ? (
                            <>
                                {/* Single Render Source: Global Centered Active Card Carousel */}
                                <div className="mt-4">
                                    <CenteredCardCarousel
                                        items={filteredServices}
                                        getItemKey={(service) => service.id}
                                        slideWidthClassName="w-[84vw] max-w-[325px] sm:w-[350px] lg:w-[380px]"
                                        autoplayDelay={4000}
                                        ariaLabel="Koleksi layanan NDS"
                                        renderItem={(service, idx, isActive) => (
                                            <div className="h-[285px] w-full">
                                                <ServiceCard
                                                    service={service}
                                                    layoutSize={service.layout_size ?? "wide"}
                                                    className="h-full w-full"
                                                />
                                            </div>
                                        )}
                                    />
                                </div>

                                {/* Pagination */}
                                {services.last_page > 1 && (
                                    <div className="mt-10 flex justify-center">
                                        <nav className="flex items-center gap-2">
                                            {services.current_page > 1 && (
                                                <Link
                                                    href={route("services.index", {
                                                        page: services.current_page - 1,
                                                        ...(search ? { q: search } : {}),
                                                    })}
                                                    className="btn-secondary touch-target h-11 rounded-full px-5"
                                                >
                                                    Sebelumnya
                                                </Link>
                                            )}
                                            <span className="text-sm text-body-text flex items-center h-11">
                                                Halaman {services.current_page} dari {services.last_page}
                                            </span>
                                            {services.current_page < services.last_page && (
                                                <Link
                                                    href={route("services.index", {
                                                        page: services.current_page + 1,
                                                        ...(search ? { q: search } : {}),
                                                    })}
                                                    className="btn-primary touch-target h-11 rounded-full px-5"
                                                >
                                                    Berikutnya
                                                    <ArrowRight className="h-4 w-4 ml-2" />
                                                </Link>
                                            )}
                                        </nav>
                                    </div>
                                )}
                            </>
                        ) : (
                            <div className="flex flex-col items-center py-16 text-center">
                                <p className="text-lg font-semibold text-navy">
                                    {search ? `Tidak ada layanan yang cocok dengan "${search}".` : "Belum ada layanan yang ditayangkan."}
                                </p>
                                <p className="mt-2 text-sm text-body-text">
                                    {search
                                        ? "Coba kata kunci lain, misalnya nama layanan seperti jaringan atau aplikasi."
                                        : "Silakan cek kembali di lain waktu."}
                                </p>
                                {search && (
                                    <Button variant="secondary" className="mt-6" onClick={() => setSearch("")}>
                                        Hapus pencarian
                                    </Button>
                                )}
                            </div>
                        )}
                    </div>
                </div>
            </section>
        </>
    );
}

export default withFrontendLayout(ServicesIndex);