import { Head, Link, router } from '@inertiajs/react';
import { useLaravelReactI18n } from 'laravel-react-i18n';
import {
    ArrowDownWideNarrow,
    ChevronLeft,
    ChevronRight,
    Search,
    SearchX,
    X,
} from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import BlogCard from '@/components/frontend/BlogCard';
import { Combobox } from '@/components/ui/combobox';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { cn } from '@/lib/utils';
import type { BlogCategoryPublic, PostPublic } from '@/types/models';

type PaginationLink = {
    url: string | null;
    label: string;
    active: boolean;
};

type PaginatedPosts = {
    data: PostPublic[];
    links: PaginationLink[];
    current_page: number;
    last_page: number;
    prev_page_url: string | null;
    next_page_url: string | null;
    total: number;
    from: number | null;
    to: number | null;
};

type BlogFilters = {
    search: string;
    sort: string;
    categories: string[];
};

type Props = {
    posts: PaginatedPosts;
    categories: BlogCategoryPublic[];
    filters: BlogFilters;
    locale: string;
    seo: {
        title: string;
        description: string;
    };
};

const SORT_OPTIONS = [
    { value: 'newest', labelKey: 'blog.sort_newest' },
    { value: 'oldest', labelKey: 'blog.sort_oldest' },
    { value: 'title_asc', labelKey: 'blog.sort_title_asc' },
    { value: 'title_desc', labelKey: 'blog.sort_title_desc' },
] as const;

/**
 * Halaman Blog (/{locale}/blog) — grid published + toolbar profesional:
 * pencarian live, sort, filter kategori multi-select (dropdown), count hasil.
 */
export default function Blog({
    posts,
    categories,
    filters,
    locale,
    seo,
}: Props) {
    const { t } = useLaravelReactI18n();
    const isEn = locale === 'en';

    const [searchInput, setSearchInput] = useState(filters.search);
    const debounceRef = useRef<number | null>(null);

    useEffect(() => {
        return () => {
            if (debounceRef.current) {
                window.clearTimeout(debounceRef.current);
            }
        };
    }, []);

    /** Navigasi dengan filter — tanpa reload halaman penuh (Inertia partial). */
    const navigate = (patch: Partial<BlogFilters>, page = 1) => {
        const next = { ...filters, ...patch };
        const query: Record<string, string> = { page: String(page) };

        if (next.search) {
            query.search = next.search;
        }

        if (next.sort !== 'newest') {
            query.sort = next.sort;
        }

        if (next.categories.length > 0) {
            query.categories = next.categories.join(',');
        }

        router.get(`/${locale}/blog`, query, {
            preserveState: true,
            preserveScroll: true,
            only: ['posts', 'filters'],
        });
    };

    const handleSearchChange = (value: string) => {
        setSearchInput(value);

        if (debounceRef.current) {
            window.clearTimeout(debounceRef.current);
        }

        debounceRef.current = window.setTimeout(() => {
            navigate({ search: value.trim() });
        }, 350);
    };

    const resetFilters = () => {
        setSearchInput('');
        navigate({ search: '', sort: 'newest', categories: [] });
    };

    const hasActiveFilters =
        filters.search !== '' ||
        filters.sort !== 'newest' ||
        filters.categories.length > 0;

    return (
        <>
            <Head title={seo.title}>
                <meta name="description" content={seo.description} />
            </Head>

            <section className="mx-auto w-full max-w-7xl px-4 py-16 sm:px-6 sm:py-20">
                <div className="max-w-2xl">
                    <p className="text-sm font-medium tracking-wider text-primary uppercase">
                        {t('nav.blog')}
                    </p>
                    <h1 className="mt-2 font-poppins text-3xl font-bold tracking-tight sm:text-4xl">
                        {t('blog.title')}
                    </h1>
                    <p className="mt-4 text-lg text-muted-foreground">
                        {t('blog.subtitle')}
                    </p>
                </div>

                {/* Toolbar: search + sort + kategori multi-select */}
                <div className="mt-8 flex flex-wrap items-center gap-2.5">
                    <div className="relative min-w-56 flex-1">
                        <Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
                        <input
                            type="search"
                            value={searchInput}
                            onChange={(event) =>
                                handleSearchChange(event.target.value)
                            }
                            placeholder={t('blog.search_placeholder')}
                            aria-label={t('blog.search_aria')}
                            className="h-10 w-full rounded-lg border bg-background pr-9 pl-9 text-sm shadow-sm focus:ring-2 focus:ring-ring focus:outline-none"
                        />
                        {searchInput !== '' && (
                            <button
                                type="button"
                                aria-label={isEn ? 'Clear search' : 'Hapus pencarian'}
                                onClick={() => handleSearchChange('')}
                                className="absolute top-1/2 right-2.5 -translate-y-1/2 rounded-full p-0.5 text-muted-foreground transition-colors hover:text-foreground"
                            >
                                <X className="size-4" />
                            </button>
                        )}
                    </div>

                    <Select
                        value={filters.sort}
                        onValueChange={(value) => navigate({ sort: value })}
                    >
                        <SelectTrigger
                            className="h-10 w-40"
                            aria-label={t('blog.sort')}
                        >
                            <ArrowDownWideNarrow className="size-4 text-muted-foreground" />
                            <SelectValue placeholder={t('blog.sort')} />
                        </SelectTrigger>
                        <SelectContent>
                            {SORT_OPTIONS.map((option) => (
                                <SelectItem
                                    key={option.value}
                                    value={option.value}
                                >
                                    {t(option.labelKey)}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>

                    {categories.length > 0 && (
                        <Combobox
                            multiple
                            options={categories.map((category) => ({
                                value: category.slug,
                                label: category.name,
                            }))}
                            value={filters.categories}
                            onValueChange={(value) =>
                                navigate({
                                    categories: Array.isArray(value)
                                        ? value
                                        : [],
                                })
                            }
                            clearOptionLabel={t('blog.categories_all')}
                            placeholder={t('blog.categories')}
                            searchPlaceholder={t('blog.categories_search')}
                            emptyText={t('blog.categories_empty')}
                            className="w-auto rounded-lg font-medium"
                        />
                    )}

                    {hasActiveFilters && (
                        <button
                            type="button"
                            onClick={resetFilters}
                            className="inline-flex h-10 items-center gap-1.5 rounded-lg px-2.5 text-sm font-medium text-muted-foreground transition-colors hover:text-foreground"
                        >
                            <X className="size-4" />
                            {t('blog.reset')}
                        </button>
                    )}
                </div>

                {/* Jumlah hasil */}
                <p className="mt-5 text-sm text-muted-foreground">
                    {t('blog.results', { count: posts.total })}
                </p>

                {posts.data.length > 0 ? (
                    <>
                        <div className="mt-6 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
                            {posts.data.map((post) => (
                                <BlogCard
                                    key={post.id}
                                    title={post.title}
                                    slug={post.slug}
                                    excerpt={post.excerpt}
                                    publishedAt={post.published_at}
                                    categories={post.categories}
                                    authorName={post.author}
                                    image={post.image}
                                    locale={locale}
                                    views={post.views}
                                />
                            ))}
                        </div>

                        {posts.last_page > 1 && (
                            <nav
                                className="mt-12 flex items-center justify-center gap-1"
                                aria-label="Pagination"
                            >
                                <PaginationArrow
                                    href={posts.prev_page_url}
                                    disabled={!posts.prev_page_url}
                                    ariaLabel={isEn ? 'Previous page' : 'Halaman sebelumnya'}
                                >
                                    <ChevronLeft className="size-4" />
                                </PaginationArrow>

                                {posts.links
                                    .filter(
                                        (link) =>
                                            link.url !== null &&
                                            /^\d+$/.test(link.label),
                                    )
                                    .map((link, index) => (
                                        <Link
                                            key={`${link.label}-${index}`}
                                            href={link.url ?? '#'}
                                            preserveScroll
                                            className={cn(
                                                'inline-flex size-9 items-center justify-center rounded-md text-sm transition-colors',
                                                link.active
                                                    ? 'bg-primary font-semibold text-primary-foreground'
                                                    : 'text-muted-foreground hover:bg-muted hover:text-foreground',
                                            )}
                                        >
                                            {link.label}
                                        </Link>
                                    ))}

                                <PaginationArrow
                                    href={posts.next_page_url}
                                    disabled={!posts.next_page_url}
                                    ariaLabel={isEn ? 'Next page' : 'Halaman berikutnya'}
                                >
                                    <ChevronRight className="size-4" />
                                </PaginationArrow>
                            </nav>
                        )}
                    </>
                ) : (
                    <div className="mt-10 flex flex-col items-center gap-2 rounded-lg border py-16 text-center">
                        <SearchX className="size-10 text-muted-foreground" />
                        <p className="text-sm text-muted-foreground">
                            {t('blog.results_empty')}
                        </p>
                    </div>
                )}
            </section>
        </>
    );
}

function PaginationArrow({
    href,
    disabled,
    ariaLabel,
    children,
}: {
    href: string | null;
    disabled: boolean;
    ariaLabel: string;
    children: ReactNode;
}) {
    if (disabled || !href) {
        return (
            <span className="inline-flex size-9 items-center justify-center rounded-md text-muted-foreground/40">
                {children}
            </span>
        );
    }

    return (
        <Link
            href={href}
            preserveScroll
            aria-label={ariaLabel}
            className="inline-flex size-9 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
        >
            {children}
        </Link>
    );
}
