import { Head, Link, router, useForm } from '@inertiajs/react';
import { Plus, Search } from 'lucide-react';
import { FormEventHandler } from 'react';

import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import AdminLayout from '@/layouts/admin-layout';
import { type Category, type PaginatedData, type Product } from '@/types';

export default function AdminProductsIndex({
    products,
    categories,
    filters,
}: {
    products: PaginatedData<Product>;
    categories: Category[];
    filters: Record<string, string>;
}) {
    const { data, setData, get } = useForm({ search: filters.search ?? '' });

    const applyFilters: FormEventHandler = (e) => {
        e.preventDefault();
        get(route('admin.products.index'), { preserveState: true });
    };

    const toggleStatus = (product: Product) => {
        router.post(route('admin.products.toggleStatus', product.id), {}, { preserveState: true });
    };

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

            <div className="mb-4 flex items-center gap-3">
                <form onSubmit={applyFilters} className="flex flex-1 items-center gap-2">
                    <div className="relative flex-1 max-w-sm">
                        <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                        <Input
                            placeholder="Search products…"
                            value={data.search}
                            onChange={(e) => setData('search', e.target.value)}
                            className="pl-9"
                        />
                    </div>
                    <Button type="submit" variant="secondary">Search</Button>
                </form>
                <Link href={route('admin.products.create')}>
                    <Button className="bg-indigo-600 hover:bg-indigo-700">
                        <Plus size={16} /> Add Product
                    </Button>
                </Link>
            </div>

            <Card>
                <CardContent className="p-0">
                    <div className="overflow-x-auto">
                        <table className="w-full text-sm">
                            <thead className="border-b bg-slate-50 text-xs uppercase text-slate-500">
                                <tr>
                                    <th className="px-4 py-3 text-left w-12">#</th>
                                    <th className="px-4 py-3 text-left">Product</th>
                                    <th className="px-4 py-3 text-left">SKU</th>
                                    <th className="px-4 py-3 text-left">Category</th>
                                    <th className="px-4 py-3 text-right">Price</th>
                                    <th className="px-4 py-3 text-right">Stock</th>
                                    <th className="px-4 py-3 text-center">Status</th>
                                    <th className="px-4 py-3" />
                                </tr>
                            </thead>
                            <tbody className="divide-y">
                                {products.data.map((product) => {
                                    const primaryImg = product.images?.find((i) => i.is_primary) ?? product.images?.[0];
                                    return (
                                        <tr key={product.id} className="hover:bg-slate-50">
                                            <td className="px-4 py-3">
                                                {primaryImg ? (
                                                    <img src={`/storage/${primaryImg.image}`} className="h-10 w-10 rounded object-cover" alt="" />
                                                ) : (
                                                    <div className="h-10 w-10 rounded bg-slate-200" />
                                                )}
                                            </td>
                                            <td className="px-4 py-3">
                                                <div className="font-medium">{product.name}</div>
                                                {product.brand && <div className="text-xs text-slate-400">{product.brand.name}</div>}
                                            </td>
                                            <td className="px-4 py-3 font-mono text-xs text-slate-500">{product.sku}</td>
                                            <td className="px-4 py-3 text-slate-500">{product.category?.name}</td>
                                            <td className="px-4 py-3 text-right">
                                                {product.compare_price && Number(product.compare_price) > Number(product.price) ? (
                                                    <div className="flex flex-col items-end gap-0.5">
                                                        <span className="font-semibold">৳{Number(product.price).toLocaleString()}</span>
                                                        <span className="text-xs text-slate-400 line-through">৳{Number(product.compare_price).toLocaleString()}</span>
                                                        <span className="rounded bg-red-100 px-1.5 py-0.5 text-[10px] font-bold text-red-600">
                                                            -{Math.round(((Number(product.compare_price) - Number(product.price)) / Number(product.compare_price)) * 100)}%
                                                        </span>
                                                    </div>
                                                ) : (
                                                    <span className="font-semibold">৳{Number(product.price).toLocaleString()}</span>
                                                )}
                                            </td>
                                            <td className="px-4 py-3 text-right">
                                                <span className={product.stock_qty <= product.low_stock_alert ? 'font-semibold text-red-600' : ''}>
                                                    {product.stock_qty}
                                                </span>
                                            </td>
                                            <td className="px-4 py-3 text-center">
                                                <button
                                                    onClick={() => toggleStatus(product)}
                                                    className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${product.status ? 'bg-green-100 text-green-700' : 'bg-slate-100 text-slate-500'}`}
                                                >
                                                    {product.status ? 'Active' : 'Inactive'}
                                                </button>
                                            </td>
                                            <td className="px-4 py-3">
                                                <div className="flex gap-2">
                                                    <Link href={route('admin.products.edit', product.id)} className="text-xs text-indigo-600 hover:underline">Edit</Link>
                                                    <Link href={route('admin.products.show', product.id)} className="text-xs text-slate-500 hover:underline">View</Link>
                                                </div>
                                            </td>
                                        </tr>
                                    );
                                })}
                                {products.data.length === 0 && (
                                    <tr><td colSpan={8} className="px-4 py-10 text-center text-slate-400">No products found</td></tr>
                                )}
                            </tbody>
                        </table>
                    </div>

                    {products.last_page > 1 && (
                        <div className="flex items-center justify-between border-t px-4 py-3 text-sm text-slate-500">
                            <span>Showing {products.from}–{products.to} of {products.total}</span>
                            <div className="flex gap-1">
                                {products.links.map((link, i) => (
                                    <button
                                        key={i}
                                        disabled={!link.url}
                                        onClick={() => link.url && router.visit(link.url)}
                                        className={`rounded px-2 py-1 text-xs ${link.active ? 'bg-indigo-600 text-white' : 'hover:bg-slate-100 disabled:opacity-40'}`}
                                        dangerouslySetInnerHTML={{ __html: link.label }}
                                    />
                                ))}
                            </div>
                        </div>
                    )}
                </CardContent>
            </Card>
        </AdminLayout>
    );
}
