import { Head, Link, router, usePage } from '@inertiajs/react';
import { ImageIcon, Pencil, Plus, Trash2 } from 'lucide-react';
import {
    PaginationControls,
    type PaginatedData,
    SortableHeader,
    type TableFilters,
} from '@/components/data-table-controls';
import Heading from '@/components/heading';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import type { Auth } from '@/types';

type Option = {
    id: number;
    name: string;
};

type Product = {
    id: number;
    name: string;
    slug: string;
    sku: string | null;
    price: string;
    stock: number;
    feature_image_url: string | null;
    is_active: boolean;
    variations_count: number;
    store: Option;
    category: Option;
    brand: Option;
};

type PageProps = {
    auth: Auth;
    products: PaginatedData<Product>;
    filters: TableFilters;
};

export default function ProductsIndex({ products, filters }: PageProps) {
    const { auth } = usePage<PageProps>().props;
    const can = (permission: string) => auth.permissions.includes(permission);

    const destroy = (product: Product) => {
        if (!window.confirm(`Delete ${product.name}?`)) {
            return;
        }

        router.delete(`/products/${product.id}`, { preserveScroll: true });
    };

    return (
        <>
            <Head title="Products" />

            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4">
                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                    <Heading
                        title="Products"
                        description="Manage shop products, images, and variations."
                    />

                    {can('products.create') && (
                        <Button asChild>
                            <Link href="/products/create">
                                <Plus />
                                New product
                            </Link>
                        </Button>
                    )}
                </div>

                <div className="overflow-hidden rounded-lg border">
                    <table className="w-full text-sm">
                        <thead className="bg-muted/50 text-left">
                            <tr>
                                <th className="px-4 py-3 font-medium">Image</th>
                                <SortableHeader
                                    basePath="/products"
                                    column="name"
                                    filters={filters}
                                    className="px-4 py-3"
                                >
                                    Product
                                </SortableHeader>
                                <th className="px-4 py-3 font-medium">Store</th>
                                <th className="px-4 py-3 font-medium">
                                    Category
                                </th>
                                <th className="px-4 py-3 font-medium">Brand</th>
                                <SortableHeader
                                    basePath="/products"
                                    column="price"
                                    filters={filters}
                                    className="px-4 py-3"
                                >
                                    Price
                                </SortableHeader>
                                <SortableHeader
                                    basePath="/products"
                                    column="stock"
                                    filters={filters}
                                    className="px-4 py-3"
                                >
                                    Stock
                                </SortableHeader>
                                <th className="px-4 py-3 font-medium">
                                    Variations
                                </th>
                                <SortableHeader
                                    basePath="/products"
                                    column="is_active"
                                    filters={filters}
                                    className="px-4 py-3"
                                >
                                    Status
                                </SortableHeader>
                                <th className="w-28 px-4 py-3 text-right font-medium">
                                    Actions
                                </th>
                            </tr>
                        </thead>
                        <tbody className="divide-y">
                            {products.data.map((product) => (
                                <tr key={product.id}>
                                    <td className="px-4 py-3">
                                        {product.feature_image_url ? (
                                            <img
                                                src={product.feature_image_url}
                                                alt={product.name}
                                                className="size-12 rounded-md border object-cover"
                                            />
                                        ) : (
                                            <div className="flex size-12 items-center justify-center rounded-md border bg-muted">
                                                <ImageIcon className="size-5 text-muted-foreground" />
                                            </div>
                                        )}
                                    </td>
                                    <td className="px-4 py-3">
                                        <div className="font-medium">
                                            {product.name}
                                        </div>
                                        <div className="text-xs text-muted-foreground">
                                            {product.sku ?? product.slug}
                                        </div>
                                    </td>
                                    <td className="px-4 py-3 text-muted-foreground">
                                        {product.store.name}
                                    </td>
                                    <td className="px-4 py-3 text-muted-foreground">
                                        {product.category.name}
                                    </td>
                                    <td className="px-4 py-3 text-muted-foreground">
                                        {product.brand.name}
                                    </td>
                                    <td className="px-4 py-3 text-muted-foreground">
                                        {product.price}
                                    </td>
                                    <td className="px-4 py-3 text-muted-foreground">
                                        {product.stock}
                                    </td>
                                    <td className="px-4 py-3 text-muted-foreground">
                                        {product.variations_count}
                                    </td>
                                    <td className="px-4 py-3">
                                        <Badge
                                            variant={
                                                product.is_active
                                                    ? 'secondary'
                                                    : 'outline'
                                            }
                                        >
                                            {product.is_active
                                                ? 'Active'
                                                : 'Inactive'}
                                        </Badge>
                                    </td>
                                    <td className="px-4 py-3">
                                        <div className="flex justify-end gap-2">
                                            {can('products.update') && (
                                                <Button
                                                    variant="outline"
                                                    size="icon"
                                                    asChild
                                                >
                                                    <Link
                                                        href={`/products/${product.id}/edit`}
                                                    >
                                                        <Pencil />
                                                        <span className="sr-only">
                                                            Edit
                                                        </span>
                                                    </Link>
                                                </Button>
                                            )}
                                            {can('products.delete') && (
                                                <Button
                                                    variant="destructive"
                                                    size="icon"
                                                    onClick={() =>
                                                        destroy(product)
                                                    }
                                                >
                                                    <Trash2 />
                                                    <span className="sr-only">
                                                        Delete
                                                    </span>
                                                </Button>
                                            )}
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                    <PaginationControls
                        basePath="/products"
                        filters={filters}
                        meta={products}
                    />
                </div>
            </div>
        </>
    );
}

ProductsIndex.layout = {
    breadcrumbs: [
        {
            title: 'Products',
            href: '/products',
        },
    ],
};
