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

import { SeoHead } from '@/components/seo/seo-head';
import { PublicLayout } from '@/layouts/public-layout';

type CategoryCard = {
    id: number;
    name: string;
    slug: string;
    description: string | null;
    published_products_count: number;
};

type ProductCard = {
    id: number;
    name: string;
    slug: string;
    brand: string | null;
    short_description: string | null;
    description: string | null;
    category: string | null;
    category_slug: string | null;
    media_url: string | null;
};

type HomeProps = {
    seo: {
        title: string;
        description: string;
        canonical_url: string;
        schema: Record<string, unknown>;
    };
    categories: CategoryCard[];
    products: ProductCard[];
    filters: {
        category: string | null;
        search: string | null;
    };
    selectedCategory: {
        id: number;
        name: string;
        slug: string;
    } | null;
};

export default function Home({
    seo,
    categories,
    products,
    filters,
    selectedCategory,
}: HomeProps) {
    const [search, setSearch] = useState(filters.search || '');

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

        const params: Record<string, string> = {};

        if (selectedCategory) {
            params.category = selectedCategory.slug;
        }

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

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

    const clearSearch = () => {
        const params: Record<string, string> = {};

        if (selectedCategory) {
            params.category = selectedCategory.slug;
        }

        setSearch('');

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

    return (
        <PublicLayout title={seo.title}>
            <SeoHead
                title={seo.title}
                description={seo.description}
                canonicalUrl={seo.canonical_url}
                jsonLd={seo.schema}
            />

            <section className="grid gap-6 rounded-3xl border border-border bg-card p-5 shadow-xl sm:p-8 lg:grid-cols-2">
                <div className="space-y-4">
                    <p className="inline-flex rounded-full border border-primary/30 bg-primary/10 px-3 py-1 text-xs tracking-wide text-primary uppercase">
                        Technical catalog + e-commerce
                    </p>
                    <h1 className="text-2xl leading-tight font-semibold text-main sm:text-3xl lg:text-4xl">
                        Reliable part data, OEM references, and confident
                        purchasing.
                    </h1>
                    <p className="max-w-xl text-sm text-muted">
                        Built for workshops, mechanics, and part specialists who
                        need accurate variant and reference data before
                        ordering.
                    </p>
                    <div className="flex flex-wrap gap-2">
                        <Link
                            href="/catalog"
                            className="rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-white hover:bg-primary-hover"
                        >
                            Browse Catalog
                        </Link>
                        <Link
                            href="/admin/login"
                            className="rounded-lg border border-border px-4 py-2 text-sm font-semibold text-main hover:bg-surface"
                        >
                            Seller Login
                        </Link>
                    </div>
                </div>
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <div className="rounded-2xl bg-surface p-4">
                        <p className="text-xs tracking-wide text-muted uppercase">
                            Product Categories
                        </p>
                        <p className="mt-2 text-3xl font-semibold">
                            {categories.length}
                        </p>
                    </div>
                    <div className="rounded-2xl bg-surface p-4">
                        <p className="text-xs tracking-wide text-muted uppercase">
                            Published Products
                        </p>
                        <p className="mt-2 text-3xl font-semibold">
                            {products.length}
                        </p>
                    </div>
                </div>
            </section>

            <section className="mt-8">
                <div className="rounded-2xl border border-border bg-card p-4 shadow-sm">
                    <form
                        onSubmit={submitSearch}
                        className="grid gap-3 md:grid-cols-[1fr_auto_auto]"
                    >
                        <input
                            value={search}
                            onChange={(event) => setSearch(event.target.value)}
                            placeholder="Search by part name, brand, SKU, OEM or aftermarket number"
                            className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-main outline-none focus:border-primary"
                        />
                        <button
                            type="submit"
                            className="rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-white hover:bg-primary-hover"
                        >
                            Search
                        </button>
                        {search !== '' ? (
                            <button
                                type="button"
                                onClick={clearSearch}
                                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}
                    </form>
                </div>
            </section>

            <section className="mt-8">
                <div className="flex flex-wrap items-center justify-between gap-4">
                    <h2 className="text-xl font-semibold text-main">
                        Categories
                    </h2>
                    {selectedCategory ? (
                        <Link
                            href={
                                filters.search
                                    ? `/?search=${encodeURIComponent(filters.search)}`
                                    : '/'
                            }
                            className="rounded-lg border border-border px-3 py-1.5 text-xs font-medium text-muted hover:bg-surface hover:text-main"
                        >
                            Clear Filter: {selectedCategory.name}
                        </Link>
                    ) : null}
                </div>
                <div className="mt-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    {categories.map((category) => (
                        <Link
                            href={`/?category=${category.slug}${filters.search ? `&search=${encodeURIComponent(filters.search)}` : ''}`}
                            key={category.id}
                            className="rounded-2xl border border-border bg-card p-4 text-left shadow-sm transition hover:-translate-y-0.5 hover:shadow-md"
                        >
                            <p className="text-sm font-semibold text-main">
                                {category.name}
                            </p>
                            <p className="mt-1 text-sm text-muted">
                                {category.description ||
                                    'Technical catalog group for vehicle parts.'}
                            </p>
                            <p className="mt-3 text-xs font-medium tracking-wide text-primary uppercase">
                                {category.published_products_count} published
                                products
                            </p>
                        </Link>
                    ))}
                </div>
            </section>

            <section className="mt-8">
                <h2 className="text-xl font-semibold text-main">
                    {filters.search
                        ? `Search Results for "${filters.search}"`
                        : selectedCategory
                          ? `${selectedCategory.name} Products`
                          : 'Latest Published Products'}
                </h2>
                {products.length === 0 ? (
                    <div className="mt-4 rounded-2xl border border-dashed border-border bg-card p-8 text-center text-sm text-muted">
                        No published products match the current filters.
                    </div>
                ) : (
                    <div className="mt-4 grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
                        {products.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 sm:h-40"
                                    />
                                ) : (
                                    <div className="flex h-44 items-center justify-center bg-surface text-sm text-muted sm:h-40">
                                        No media
                                    </div>
                                )}
                                <div className="p-4">
                                    <p className="text-xs tracking-wide text-muted uppercase">
                                        {product.category || 'Uncategorized'}
                                    </p>
                                    <p className="mt-1 text-sm font-semibold text-main">
                                        {product.name}
                                    </p>
                                    {product.brand ? (
                                        <p className="mt-1 text-xs text-muted">
                                            Brand: {product.brand}
                                        </p>
                                    ) : null}
                                    <p className="mt-1 text-sm text-muted">
                                        {product.short_description ||
                                            'Technical description pending.'}
                                    </p>
                                </div>
                            </Link>
                        ))}
                    </div>
                )}
            </section>
        </PublicLayout>
    );
}
