import { Link, router, usePage } from '@inertiajs/react';
import { useState } from 'react';

import { SeoHead } from '@/components/seo/seo-head';
import { PaginationLinks } from '@/components/ui/pagination-links';
import { PublicLayout } from '@/layouts/public-layout';
import { formatMoney } from '@/lib/money';
import type { AppPageProps, PaginatedData } from '@/types';

type ProductCard = {
    id: number;
    name: string;
    slug: string;
    sku: string | null;
    brand: string | null;
    price_minor: number;
    short_description: string | null;
    category: string | null;
    category_slug: string | null;
    media_url: string | null;
    oem_numbers: string[];
    aftermarket_numbers: string[];
};

type CategoryOption = {
    id: number;
    name: string;
    slug: string;
    published_products_count: number;
};

type MakeOption = {
    id: number;
    name: string;
    slug: string;
};

type FuelTypeOption = {
    id: number;
    name: string;
    slug: string;
};

type CatalogProps = {
    seo: {
        canonical_url: string;
    };
    products: PaginatedData<ProductCard>;
    categories: CategoryOption[];
    makes: MakeOption[];
    fuelTypes: FuelTypeOption[];
    filters: {
        search: string | null;
        category: string | null;
        make: string | null;
        fuel: string | null;
        sort: 'latest' | 'name_asc' | 'name_desc';
    };
    selected: {
        category: {
            name: string;
            slug: string;
            seo_title: string | null;
            meta_description: string | null;
            meta_keywords: string | null;
        } | null;
        make: { name: string; slug: string } | null;
        fuel: { name: string; slug: string } | null;
    };
};

export default function CatalogIndex({
    seo,
    products,
    categories,
    makes,
    fuelTypes,
    filters,
    selected,
}: CatalogProps) {
    const { config } = usePage<AppPageProps>().props;
    const [search, setSearch] = useState(filters.search || '');
    const [category, setCategory] = useState(filters.category || '');
    const [make, setMake] = useState(filters.make || '');
    const [fuel, setFuel] = useState(filters.fuel || '');
    const [sort, setSort] = useState(filters.sort || 'latest');

    const submitFilters = (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();

        const params = buildCatalogQueryParams({
            search,
            category,
            make,
            fuel,
            sort,
        });

        router.get('/catalog', params, {
            preserveState: true,
            preserveScroll: true,
            replace: true,
        });
    };

    const clearFilters = () => {
        setSearch('');
        setCategory('');
        setMake('');
        setFuel('');
        setSort('latest');

        router.get(
            '/catalog',
            {},
            {
                preserveState: true,
                preserveScroll: true,
                replace: true,
            },
        );
    };

    const hasFilters =
        search !== '' ||
        category !== '' ||
        make !== '' ||
        fuel !== '' ||
        sort !== 'latest';
    const pageTitle =
        selected.category?.seo_title ||
        (selected.category
            ? `${selected.category.name} Automotive Parts`
            : 'Catalog');
    const pageDescription =
        selected.category?.meta_description ||
        (selected.category
            ? `Browse ${selected.category.name} automotive parts with fitment and reference data.`
            : 'Browse automotive parts by category, vehicle make, fuel type, and reference numbers.');

    return (
        <PublicLayout title={pageTitle}>
            <SeoHead
                title={pageTitle}
                description={pageDescription}
                canonicalUrl={seo.canonical_url}
                keywords={selected.category?.meta_keywords}
            />

            <div className="space-y-6">
                <section className="rounded-3xl border border-border bg-card p-5 shadow-sm sm:p-6">
                    <div className="flex flex-wrap items-end justify-between gap-4">
                        <div>
                            <p className="text-xs font-semibold tracking-wide text-primary uppercase">
                                Storefront
                            </p>
                            <h1 className="mt-1 text-2xl font-semibold text-main">
                                Browse Automotive Parts Catalog
                            </h1>
                            <p className="mt-1 text-sm text-muted">
                                Filter by category, vehicle make, fuel type, and
                                reference numbers.
                            </p>
                        </div>
                        <Link
                            href="/"
                            className="rounded-lg border border-border px-3 py-1.5 text-sm font-medium text-muted hover:bg-surface hover:text-main"
                        >
                            Back to Home
                        </Link>
                    </div>
                </section>

                <section className="grid gap-6 xl:grid-cols-[320px_1fr]">
                    <aside className="space-y-4">
                        <form
                            onSubmit={submitFilters}
                            className="space-y-4 rounded-2xl border border-border bg-card p-4 shadow-sm"
                        >
                            <h2 className="text-base font-semibold text-main">
                                Filters
                            </h2>

                            <div>
                                <label className="block text-sm font-medium text-main">
                                    Search
                                </label>
                                <input
                                    value={search}
                                    onChange={(event) =>
                                        setSearch(event.target.value)
                                    }
                                    placeholder="Part name, brand, SKU, OEM or aftermarket"
                                    className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-main outline-none focus:border-primary"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-main">
                                    Category
                                </label>
                                <select
                                    value={category}
                                    onChange={(event) =>
                                        setCategory(event.target.value)
                                    }
                                    className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-main outline-none focus:border-primary"
                                >
                                    <option value="">All categories</option>
                                    {categories.map((option) => (
                                        <option
                                            key={option.id}
                                            value={option.slug}
                                        >
                                            {option.name} (
                                            {option.published_products_count})
                                        </option>
                                    ))}
                                </select>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-main">
                                    Vehicle Make
                                </label>
                                <select
                                    value={make}
                                    onChange={(event) =>
                                        setMake(event.target.value)
                                    }
                                    className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-main outline-none focus:border-primary"
                                >
                                    <option value="">All makes</option>
                                    {makes.map((option) => (
                                        <option
                                            key={option.id}
                                            value={option.slug}
                                        >
                                            {option.name}
                                        </option>
                                    ))}
                                </select>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-main">
                                    Fuel Type
                                </label>
                                <select
                                    value={fuel}
                                    onChange={(event) =>
                                        setFuel(event.target.value)
                                    }
                                    className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-main outline-none focus:border-primary"
                                >
                                    <option value="">All fuel types</option>
                                    {fuelTypes.map((option) => (
                                        <option
                                            key={option.id}
                                            value={option.slug}
                                        >
                                            {option.name}
                                        </option>
                                    ))}
                                </select>
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-main">
                                    Sort
                                </label>
                                <select
                                    value={sort}
                                    onChange={(event) =>
                                        setSort(
                                            event.target
                                                .value as CatalogProps['filters']['sort'],
                                        )
                                    }
                                    className="mt-1 w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-main outline-none focus:border-primary"
                                >
                                    <option value="latest">Latest</option>
                                    <option value="name_asc">Name (A-Z)</option>
                                    <option value="name_desc">
                                        Name (Z-A)
                                    </option>
                                </select>
                            </div>

                            <div className="flex gap-2">
                                <button
                                    type="submit"
                                    className="rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-white hover:bg-primary-hover"
                                >
                                    Apply
                                </button>
                                {hasFilters ? (
                                    <button
                                        type="button"
                                        onClick={clearFilters}
                                        className="rounded-lg border border-border px-4 py-2 text-sm font-medium text-muted hover:bg-surface hover:text-main"
                                    >
                                        Clear
                                    </button>
                                ) : null}
                            </div>
                        </form>

                        <div className="rounded-2xl border border-border bg-card p-4 shadow-sm">
                            <h2 className="text-sm font-semibold tracking-wide text-muted uppercase">
                                Active Selection
                            </h2>
                            <div className="mt-2 space-y-1 text-sm text-main">
                                <p>
                                    Category: {selected.category?.name || 'All'}
                                </p>
                                <p>Make: {selected.make?.name || 'All'}</p>
                                <p>Fuel: {selected.fuel?.name || 'All'}</p>
                            </div>
                        </div>
                    </aside>

                    <div className="space-y-4">
                        <div className="flex flex-wrap items-center justify-between gap-3">
                            <p className="text-sm text-muted">
                                Showing {products.from || 0} to{' '}
                                {products.to || 0} of {products.total} parts
                            </p>
                            <PaginationLinks links={products.links} />
                        </div>

                        {products.data.length === 0 ? (
                            <div className="rounded-2xl border border-dashed border-border bg-card p-10 text-center text-sm text-muted">
                                No products match your filters.
                            </div>
                        ) : (
                            <div className="grid gap-4 sm:grid-cols-2 2xl:grid-cols-3">
                                {products.data.map((product) => (
                                    <Link
                                        key={product.id}
                                        href={`/products/${product.slug}`}
                                        className="overflow-hidden rounded-2xl border border-border bg-card shadow-sm transition hover:-translate-y-0.5 hover:shadow-md"
                                    >
                                        {product.media_url ? (
                                            <img
                                                src={product.media_url}
                                                alt={product.name}
                                                className="h-44 w-full object-cover"
                                            />
                                        ) : (
                                            <div className="flex h-44 items-center justify-center bg-surface text-sm text-muted">
                                                No media
                                            </div>
                                        )}

                                        <div className="space-y-2 p-4">
                                            <p className="text-xs tracking-wide text-muted uppercase">
                                                {product.category ||
                                                    'Uncategorized'}
                                            </p>
                                            <p className="text-sm font-semibold text-main">
                                                {product.name}
                                            </p>
                                            <p className="text-sm font-semibold text-primary">
                                                {formatMoney(
                                                    product.price_minor,
                                                    config.default_currency,
                                                )}
                                            </p>
                                            {product.sku ? (
                                                <p className="text-xs text-muted">
                                                    SKU: {product.sku}
                                                </p>
                                            ) : null}
                                            {product.brand ? (
                                                <p className="text-xs text-muted">
                                                    Brand: {product.brand}
                                                </p>
                                            ) : null}
                                            <p className="text-sm text-muted">
                                                {product.short_description ||
                                                    'Technical description pending.'}
                                            </p>

                                            {product.oem_numbers.length > 0 ? (
                                                <p className="text-xs text-muted">
                                                    OEM:{' '}
                                                    {product.oem_numbers.join(
                                                        ', ',
                                                    )}
                                                </p>
                                            ) : null}
                                            {product.aftermarket_numbers
                                                .length > 0 ? (
                                                <p className="text-xs text-muted">
                                                    Aftermarket:{' '}
                                                    {product.aftermarket_numbers.join(
                                                        ', ',
                                                    )}
                                                </p>
                                            ) : null}
                                        </div>
                                    </Link>
                                ))}
                            </div>
                        )}

                        {products.last_page > 1 ? (
                            <div className="flex justify-end">
                                <PaginationLinks links={products.links} />
                            </div>
                        ) : null}
                    </div>
                </section>
            </div>
        </PublicLayout>
    );
}

function buildCatalogQueryParams(filters: {
    search: string;
    category: string;
    make: string;
    fuel: string;
    sort: string;
}) {
    const params: Record<string, string> = {};

    if (filters.search.trim() !== '') {
        params.search = filters.search.trim();
    }

    if (filters.category !== '') {
        params.category = filters.category;
    }

    if (filters.make !== '') {
        params.make = filters.make;
    }

    if (filters.fuel !== '') {
        params.fuel = filters.fuel;
    }

    if (filters.sort !== '' && filters.sort !== 'latest') {
        params.sort = filters.sort;
    }

    return params;
}
