import { Link, router } from "@inertiajs/react";
import { route } from "ziggy-js";
import { useState } from "react";
import { Search, CalendarDays, User, BookOpen, ArrowRight, ChevronLeft, ChevronRight, X } from "lucide-react";
import { Seo } from "@/Components/Seo";
import { Button } from "@/Components/ui/button";
import { PageHero } from "@/Components/PageHero";
import { storageUrl } from "@/utils/assets";
import { ArticleCarousel } from "@/Components/ui/ArticleCarousel";
import { useGsapReveal } from "@/hooks/useGsap";
import { withFrontendLayout } from "@/utils/layout";
import type { ArticleCategory, ArticleItem, Paginated } from "@/types";

interface BlogProps {
    articles: Paginated<ArticleItem>;
    categories: ArticleCategory[];
    filters: { category?: string; q?: string };
}

function formatDate(date?: string | null) {
    if (!date) return "";
    return new Date(date).toLocaleDateString("id-ID", { day: "numeric", month: "long", year: "numeric" });
}

function Blog({ articles, categories, filters }: BlogProps) {
    useGsapReveal();

    const [search, setSearch] = useState(filters.q || "");

    const applyFilter = (key: string, value?: string) => {
        const params: Record<string, string | undefined> = { ...filters, [key]: value || undefined };
        if (key !== "q") params.q = search || undefined;
        router.get(route("blog"), params, { preserveState: true, replace: true });
    };

    return (
        <>
            <Seo
                title="Wawasan & Artikel Teknologi"
                description="Panduan praktis dan wawasan seputar infrastruktur, aplikasi, dan keamanan IT dari tim NDS."
            />

            <PageHero
                title="Artikel Teknologi"
                description="Panduan praktis seputar arsitektur IT, jaringan, server, dan keamanan."
            />

            {/* Main Listing Section */}
            <section className="bg-light-gray py-10 lg:py-16 xl:py-20">
                <div className="container-nds">
                    {/* Filter and Search Bar */}
                    <div className="gsap-reveal flex flex-col gap-4 rounded-2xl border border-border-soft bg-white p-4 shadow-subtle sm:flex-row sm:items-center sm:justify-between sm:p-5">
                        {/* Category filter pills */}
                        <div className="flex flex-wrap gap-2">
                            <button
                                type="button"
                                onClick={() => applyFilter("category", undefined)}
                                className={`inline-flex min-h-11 cursor-pointer items-center rounded-xl border px-4 text-sm font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 ${
                                    !filters.category
                                        ? "border-primary bg-primary text-white"
                                        : "border-border-soft bg-white text-navy hover:bg-electric-light hover:text-primary"
                                }`}
                            >
                                Semua Kategori
                            </button>
                            {categories.map((cat) => (
                                <button
                                    key={cat.id}
                                    type="button"
                                    onClick={() => applyFilter("category", cat.slug)}
                                    className={`inline-flex min-h-11 cursor-pointer items-center rounded-xl border px-4 text-sm font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 ${
                                        filters.category === cat.slug
                                            ? "border-primary bg-primary text-white"
                                            : "border-border-soft bg-white text-navy hover:bg-electric-light hover:text-primary"
                                    }`}
                                >
                                    {cat.name}
                                </button>
                            ))}
                        </div>

                        {/* Search Input */}
                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                applyFilter("q", search);
                            }}
                            className="relative w-full sm:w-72"
                        >
                            <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 topik artikel..."
                                className="h-11 min-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-primary focus:outline-none focus:ring-2 focus:ring-primary/30"
                                aria-label="Cari artikel"
                            />
                            {search && (
                                <button
                                    type="button"
                                    onClick={() => {
                                        setSearch("");
                                        applyFilter("q", "");
                                    }}
                                    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-primary 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-4 w-4" />
                                </button>
                            )}
                        </form>
                    </div>

                    {/* Articles Grid */}
                    {articles.data.length === 0 ? (
                        <div className="gsap-reveal mt-12 rounded-2xl border border-border-soft bg-white p-12 text-center shadow-subtle">
                            <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-light-gray text-body-text">
                                <BookOpen className="h-6 w-6 text-tech-blue" />
                            </div>
                            <h2 className="mt-4 text-lg font-bold text-navy">Tidak ada artikel ditemukan</h2>
                            <p className="mt-1.5 text-sm text-body-text">
                                Silakan gunakan kata kunci lain atau pilih kategori yang berbeda.
                            </p>
                            <div className="mt-6">
                                <Button
                                    variant="secondary"
                                    onClick={() => {
                                        setSearch("");
                                        router.get(route("blog"));
                                    }}
                                >
                                    Reset Semua Filter
                                </Button>
                            </div>
                        </div>
                    ) : (
                        <>
                            {/* Slider Carousel: Blog page with navigation but no infinite loop */}
                            <div className="mt-8">
                                <ArticleCarousel
                                    key={`${filters.category ?? "semua"}-${filters.q ?? ""}-${articles.current_page}`}
                                    items={articles.data}
                                    getItemKey={(article) => article.id}
                                    ariaLabel="Koleksi artikel dan publikasi NDS"
                                    renderItem={(article) => (
                                        <div className="h-full">
                                            <Link
                                                href={route("blog.show", article.slug)}
                                                draggable={false}
                                                className="group flex h-full flex-col overflow-hidden rounded-2xl border border-border-soft bg-white transition-all duration-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 hover:border-primary/30 hover:shadow-elevated"
                                            >
                                                <div className="relative aspect-[16/10] w-full shrink-0 overflow-hidden bg-light-gray">
                                                    {article.image ? (
                                                        <img
                                                            src={storageUrl(article.image)}
                                                            alt={article.title}
                                                            className="h-full w-full object-cover transition-transform duration-500 ease-out group-hover:scale-105"
                                                            loading="lazy"
                                                            draggable={false}
                                                        />
                                                    ) : (
                                                        <div className="h-full w-full bg-navy" />
                                                    )}
                                                    {article.category && (
                                                        <span className="absolute left-3 top-3 rounded-full bg-primary px-3 py-1 text-xs font-bold text-white shadow-xs">
                                                            {article.category.name}
                                                        </span>
                                                    )}
                                                </div>

                                                <div className="flex flex-1 flex-col p-5">
                                                    <div className="flex items-center gap-2 text-xs text-body-text">
                                                        <CalendarDays className="h-3.5 w-3.5 text-tech-blue" />
                                                        <span>{formatDate(article.published_at)}</span>
                                                    </div>

                                                    <h2 className="mt-3 line-clamp-2 text-base font-bold text-navy transition-colors group-hover:text-primary sm:text-lg">
                                                        {article.title}
                                                    </h2>

                                                    <p className="mt-2 line-clamp-3 text-xs leading-relaxed text-body-text sm:text-sm">
                                                        {article.excerpt}
                                                    </p>

                                                    <div className="mt-auto flex items-center justify-between gap-3 border-t border-border-soft/60 pt-4 text-xs">
                                                        <span className="min-w-0 truncate font-semibold text-body-text">
                                                            {article.author || "Tim NDS"}
                                                        </span>
                                                        <span className="inline-flex shrink-0 items-center gap-1 font-bold text-primary group-hover:text-primary-hover">
                                                            <span>Baca Artikel</span>
                                                            <ArrowRight className="h-3.5 w-3.5 transition-transform duration-150 group-hover:translate-x-0.5" />
                                                        </span>
                                                    </div>
                                                </div>
                                            </Link>
                                        </div>
                                    )}
                                />
                            </div>

                            {/* Pagination */}
                            {articles.last_page > 1 && (
                                <nav aria-label="Navigasi halaman artikel" className="gsap-reveal mt-12 flex items-center justify-center gap-2">
                                    {articles.current_page > 1 ? (
                                        <Link
                                            href={route("blog", { page: articles.current_page - 1, category: filters.category, q: filters.q })}
                                            className="btn-secondary touch-target h-11 w-11 rounded-xl"
                                            aria-label="Halaman sebelumnya"
                                        >
                                            <ChevronLeft className="h-4 w-4" />
                                        </Link>
                                    ) : (
                                        <span className="flex h-11 w-11 cursor-not-allowed items-center justify-center rounded-xl border border-dashed border-border-soft bg-white text-slate">
                                            <ChevronLeft className="h-4 w-4" />
                                        </span>
                                    )}

                                    {Array.from({ length: articles.last_page }, (_, i) => i + 1).map((page) => (
                                        <Link
                                            key={page}
                                            href={route("blog", { page, category: filters.category, q: filters.q })}
                                            aria-current={page === articles.current_page ? "page" : undefined}
                                            className={`flex h-11 w-11 items-center justify-center rounded-xl text-sm font-bold transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 ${
                                                page === articles.current_page
                                                    ? "bg-navy text-white shadow-xs"
                                                    : "border border-border-soft bg-white text-navy hover:bg-navy/5"
                                            }`}
                                        >
                                            {page}
                                        </Link>
                                    ))}

                                    {articles.current_page < articles.last_page ? (
                                        <Link
                                            href={route("blog", { page: articles.current_page + 1, category: filters.category, q: filters.q })}
                                            className="btn-secondary touch-target h-11 w-11 rounded-xl"
                                            aria-label="Halaman berikutnya"
                                        >
                                            <ChevronRight className="h-4 w-4" />
                                        </Link>
                                    ) : (
                                        <span className="flex h-11 w-11 cursor-not-allowed items-center justify-center rounded-xl border border-dashed border-border-soft bg-white text-slate">
                                            <ChevronRight className="h-4 w-4" />
                                        </span>
                                    )}
                                </nav>
                            )}
                        </>
                    )}
                </div>
            </section>
        </>
    );
}

export default withFrontendLayout(Blog);