import { Head, Link, router, usePage } from '@inertiajs/react';
import type { Variants } from 'framer-motion';
import { motion } from 'framer-motion';
import {
    Plus,
    Search,
    Edit,
    Trash2,
    EyeOff,
    SlidersHorizontal,
    Package,
} from 'lucide-react';
import { useState } from 'react';
import { useConfirm } from '@/components/confirm-dialog-provider';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useTranslation } from '@/hooks/use-translation';

const containerVariants: Variants = {
    hidden: { opacity: 0 },
    show: {
        opacity: 1,
        transition: { staggerChildren: 0.07 },
    },
};

const itemVariants: Variants = {
    hidden: { opacity: 0, y: 20 },
    show: {
        opacity: 1,
        y: 0,
        transition: { duration: 0.5, ease: [0.16, 1, 0.3, 1] },
    },
};

const rowVariants: Variants = {
    hidden: { opacity: 0, x: -12 },
    show: {
        opacity: 1,
        x: 0,
        transition: { duration: 0.35, ease: [0.16, 1, 0.3, 1] },
    },
};

export default function Index({
    products,
    stats,
    vendors,
    categories,
    filters,
}: any) {
    const { t } = useTranslation();
    const { auth } = usePage().props as any;
    const permissions = auth.user?.permissions || [];
    const hasPermission = (perm: string) => permissions.includes(perm);
    const confirm = useConfirm();

    const [search, setSearch] = useState(filters.search || '');
    const [vendorId, setVendorId] = useState(filters.vendor_id || '');
    const [categoryId, setCategoryId] = useState(filters.category_id || '');
    const [status, setStatus] = useState(filters.status || '');

    const handleSearchSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        router.get(
            '/products',
            { search, vendor_id: vendorId, category_id: categoryId, status },
            { preserveState: true, replace: true },
        );
    };

    const handleFilterChange = (key: string, value: string) => {
        const queryParams = {
            search,
            vendor_id: vendorId,
            category_id: categoryId,
            status,
            [key]: value,
        };

        if (key === 'vendor_id') {
            setVendorId(value);
        }

        if (key === 'category_id') {
            setCategoryId(value);
        }

        if (key === 'status') {
            setStatus(value);
        }

        router.get('/products', queryParams, {
            preserveState: true,
            replace: true,
        });
    };

    const handleDelete = async (id: number) => {
        const confirmed = await confirm({
            title: t('products.delete_product'),
            description: t('products.confirm_delete'),
            variant: 'destructive',
            confirmText: t('common.delete'),
        });

        if (confirmed) {
            router.delete(`/products/${id}`);
        }
    };

    const formatCurrency = (val: number) => {
        return `৳${new Intl.NumberFormat('en-US', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
        }).format(val)}`;
    };

    const productList = Array.isArray(products)
        ? products
        : products?.data || [];
    const currentPage =
        products?.current_page || products?.meta?.current_page || 1;
    const lastPage = products?.last_page || products?.meta?.last_page || 1;
    const paginationLinks = Array.isArray(products?.meta?.links)
        ? products.meta.links
        : Array.isArray(products?.links)
          ? products.links
          : [];

    const totalProducts =
        stats?.total_products ??
        products?.total ??
        products?.meta?.total ??
        productList.length;
    const activeProducts =
        stats?.active_products ??
        productList.filter((p: any) => p.status === 'active').length;
    const avgVendorPrice =
        stats?.avg_vendor_price ??
        (productList.length > 0
            ? productList.reduce(
                  (s: number, p: any) => s + (p.vendor_price || 0),
                  0,
              ) / productList.length
            : 0);
    const avgSellPrice =
        stats?.avg_sell_price ??
        (productList.length > 0
            ? productList.reduce(
                  (s: number, p: any) => s + (p.default_sell_price || 0),
                  0,
              ) / productList.length
            : 0);

    const categoryList = Array.isArray(categories)
        ? categories
        : categories?.data || [];
    const vendorList = Array.isArray(vendors) ? vendors : vendors?.data || [];

    return (
        <>
            <Head title={t('products.title')} />
            <motion.div
                className="flex flex-1 flex-col gap-6 p-4 sm:p-6"
                variants={containerVariants}
                initial="hidden"
                animate="show"
            >
                {/* Header */}
                <motion.div
                    variants={itemVariants}
                    className="flex flex-col justify-between gap-4 sm:flex-row sm:items-center"
                >
                    <div>
                        <div className="mb-1 flex items-center gap-3">
                            <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-emerald-500 to-teal-600 shadow-lg shadow-emerald-500/20">
                                <Package className="size-5 text-white" />
                            </div>
                            <h1 className="text-3xl font-extrabold tracking-tight text-foreground">
                                {t('products.title')}
                            </h1>
                        </div>
                        <p className="ml-[52px] text-sm text-muted-foreground">
                            {t('products.manage_desc')}
                        </p>
                    </div>
                    {hasPermission('create_products') && (
                        <Button
                            asChild
                            className="rounded-xl border-0 bg-gradient-to-r from-emerald-600 to-teal-600 text-white shadow-lg shadow-emerald-500/20 hover:from-emerald-700 hover:to-teal-700"
                        >
                            <Link
                                href="/products/create"
                                className="flex items-center gap-1.5"
                            >
                                <Plus className="size-4" />
                                <span>{t('products.add_product')}</span>
                            </Link>
                        </Button>
                    )}
                </motion.div>

                {/* Quick Stats */}
                <motion.div
                    variants={itemVariants}
                    className="grid grid-cols-2 gap-4 md:grid-cols-4"
                >
                    <div className="rounded-2xl border border-border bg-card/60 p-4 backdrop-blur-md">
                        <span className="text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
                            {t('products.title')}
                        </span>
                        <p className="mt-1 text-2xl font-black text-foreground">
                            {totalProducts}
                        </p>
                    </div>
                    <div className="rounded-2xl border border-border bg-card/60 p-4 backdrop-blur-md">
                        <span className="text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
                            {t('products.active')}
                        </span>
                        <p className="mt-1 text-2xl font-black text-emerald-500">
                            {activeProducts}
                        </p>
                    </div>
                    <div className="rounded-2xl border border-border bg-card/60 p-4 backdrop-blur-md">
                        <span className="text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
                            {t('products.avg_vendor_price')}
                        </span>
                        <p className="mt-1 text-2xl font-black text-blue-500">
                            {formatCurrency(avgVendorPrice)}
                        </p>
                    </div>
                    <div className="rounded-2xl border border-border bg-card/60 p-4 backdrop-blur-md">
                        <span className="text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">
                            {t('products.avg_sell_price')}
                        </span>
                        <p className="mt-1 text-2xl font-black text-amber-500">
                            {formatCurrency(avgSellPrice)}
                        </p>
                    </div>
                </motion.div>

                {/* Filters Panel */}
                <motion.div
                    variants={itemVariants}
                    className="flex flex-col gap-4 rounded-2xl border border-border bg-card/45 p-4 backdrop-blur-md lg:flex-row lg:items-center"
                >
                    <form
                        onSubmit={handleSearchSubmit}
                        className="flex flex-1 items-center gap-2"
                    >
                        <div className="relative max-w-md flex-1">
                            <Search className="absolute top-1/2 left-3.5 size-4 -translate-y-1/2 text-muted-foreground" />
                            <Input
                                value={search}
                                onChange={(e) => setSearch(e.target.value)}
                                placeholder={t('products.search_placeholder')}
                                className="h-10 rounded-xl border-border/50 bg-background/50 pl-10 transition-colors focus:bg-background"
                            />
                        </div>
                        <Button
                            type="submit"
                            variant="secondary"
                            className="h-10 rounded-xl"
                        >
                            {t('common.search')}
                        </Button>
                    </form>

                    <div className="flex flex-wrap items-center gap-3">
                        <SlidersHorizontal className="hidden size-4 text-muted-foreground sm:block" />

                        <select
                            value={categoryId}
                            onChange={(e) =>
                                handleFilterChange(
                                    'category_id',
                                    e.target.value,
                                )
                            }
                            className="h-10 rounded-xl border border-input bg-card px-3 text-sm transition-all focus:ring-2 focus:ring-ring focus:outline-none"
                        >
                            <option value="">
                                {t('products.all_categories')}
                            </option>
                            {categoryList.map((c: any) => (
                                <option key={c.id} value={c.id}>
                                    {c.name}
                                </option>
                            ))}
                        </select>

                        <select
                            value={vendorId}
                            onChange={(e) =>
                                handleFilterChange('vendor_id', e.target.value)
                            }
                            className="h-10 rounded-xl border border-input bg-card px-3 text-sm transition-all focus:ring-2 focus:ring-ring focus:outline-none"
                        >
                            <option value="">
                                {t('products.all_vendors')}
                            </option>
                            {vendorList.map((v: any) => (
                                <option key={v.id} value={v.id}>
                                    {v.name}
                                </option>
                            ))}
                        </select>

                        <select
                            value={status}
                            onChange={(e) =>
                                handleFilterChange('status', e.target.value)
                            }
                            className="h-10 rounded-xl border border-input bg-card px-3 text-sm transition-all focus:ring-2 focus:ring-ring focus:outline-none"
                        >
                            <option value="">
                                {t('products.all_statuses')}
                            </option>
                            <option value="active">
                                {t('products.active')}
                            </option>
                            <option value="inactive">
                                {t('products.inactive')}
                            </option>
                        </select>
                    </div>
                </motion.div>

                {/* Table Card */}
                <motion.div
                    variants={itemVariants}
                    className="overflow-hidden rounded-2xl border border-border bg-card shadow-sm"
                >
                    <div className="overflow-x-auto">
                        <table className="w-full text-left text-sm">
                            <thead className="border-b border-border bg-gradient-to-r from-neutral-900/5 to-neutral-900/[0.02] text-[11px] font-semibold tracking-wider text-muted-foreground uppercase dark:from-neutral-100/5 dark:to-neutral-100/[0.02]">
                                <tr>
                                    <th className="px-6 py-4">
                                        {t('products.product_name')}
                                    </th>
                                    <th className="px-6 py-4">
                                        {t('products.category')} /{' '}
                                        {t('products.brand')}
                                    </th>
                                    <th className="px-6 py-4">
                                        {t('products.vendor')}
                                    </th>
                                    <th className="px-6 py-4 text-right">
                                        {t('products.cost_price')}
                                    </th>
                                    <th className="px-6 py-4 text-right">
                                        {t('products.sale_price')}
                                    </th>
                                    <th className="px-6 py-4 text-center">
                                        {t('products.status')}
                                    </th>
                                    <th className="px-6 py-4 text-center">
                                        {t('common.actions')}
                                    </th>
                                </tr>
                            </thead>
                            <motion.tbody
                                className="divide-y divide-border"
                                variants={containerVariants}
                                initial="hidden"
                                animate="show"
                            >
                                {productList.length > 0 ? (
                                    productList.map((prod: any) => {
                                        const margin =
                                            prod.default_sell_price > 0
                                                ? ((prod.default_sell_price -
                                                      prod.vendor_price) /
                                                      prod.default_sell_price) *
                                                  100
                                                : 0;

                                        return (
                                            <motion.tr
                                                key={prod.id}
                                                variants={rowVariants}
                                                className="group transition-colors hover:bg-emerald-500/[0.03] dark:hover:bg-emerald-400/[0.05]"
                                            >
                                                <td className="px-6 py-4">
                                                    <div className="flex items-center gap-3">
                                                        <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-emerald-500/10 to-teal-500/10 text-sm font-bold text-emerald-600 dark:text-emerald-400">
                                                            {prod.name
                                                                ?.charAt(0)
                                                                ?.toUpperCase()}
                                                        </div>
                                                        <div>
                                                            <div className="font-semibold text-foreground">
                                                                {prod.name}
                                                            </div>
                                                            <div className="max-w-[200px] truncate text-[11px] text-muted-foreground/70">
                                                                {prod.description ||
                                                                    t(
                                                                        'products.no_description',
                                                                    )}
                                                            </div>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4">
                                                    <div className="font-medium text-foreground">
                                                        {prod.category?.name ||
                                                            'N/A'}
                                                    </div>
                                                    <div className="text-[11px] text-muted-foreground">
                                                        {prod.brand?.name ||
                                                            'N/A'}
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4 font-medium text-muted-foreground">
                                                    {prod.vendor?.name || 'N/A'}
                                                </td>
                                                <td className="px-6 py-4 text-right font-medium text-muted-foreground tabular-nums">
                                                    {formatCurrency(
                                                        prod.vendor_price,
                                                    )}
                                                </td>
                                                <td className="px-6 py-4 text-right tabular-nums">
                                                    <div className="font-bold text-foreground">
                                                        {formatCurrency(
                                                            prod.default_sell_price,
                                                        )}
                                                    </div>
                                                    <div
                                                        className={`text-[10px] font-semibold ${margin > 0 ? 'text-emerald-500' : 'text-rose-500'}`}
                                                    >
                                                        {margin > 0 ? '+' : ''}
                                                        {margin.toFixed(1)}%
                                                        {t('products.margin')}
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4 text-center">
                                                    <span
                                                        className={`inline-flex items-center rounded-full px-2.5 py-1 text-[11px] font-semibold tracking-wide ${prod.status === 'active' ? 'bg-emerald-500/10 text-emerald-600 ring-1 ring-emerald-500/20 dark:text-emerald-400' : 'bg-neutral-500/10 text-neutral-500 ring-1 ring-neutral-500/20'}`}
                                                    >
                                                        {prod.status ===
                                                        'active'
                                                            ? t(
                                                                  'products.active',
                                                              )
                                                            : t(
                                                                  'products.inactive',
                                                              )}
                                                    </span>
                                                </td>
                                                <td className="px-6 py-4 text-center">
                                                    <div className="flex items-center justify-center gap-1 opacity-60 transition-opacity group-hover:opacity-100">
                                                        {hasPermission(
                                                            'edit_products',
                                                        ) && (
                                                            <Button
                                                                asChild
                                                                size="icon"
                                                                variant="ghost"
                                                                className="h-8 w-8 rounded-lg text-muted-foreground hover:bg-emerald-500/10 hover:text-emerald-600"
                                                            >
                                                                <Link
                                                                    href={`/products/${prod.id}/edit`}
                                                                >
                                                                    <Edit className="size-4" />
                                                                </Link>
                                                            </Button>
                                                        )}
                                                        {hasPermission(
                                                            'delete_products',
                                                        ) && (
                                                            <Button
                                                                onClick={() =>
                                                                    handleDelete(
                                                                        prod.id,
                                                                    )
                                                                }
                                                                size="icon"
                                                                variant="ghost"
                                                                className="h-8 w-8 rounded-lg text-rose-500 hover:bg-rose-500/10 hover:text-rose-600"
                                                            >
                                                                <Trash2 className="size-4" />
                                                            </Button>
                                                        )}
                                                    </div>
                                                </td>
                                            </motion.tr>
                                        );
                                    })
                                ) : (
                                    <motion.tr variants={rowVariants}>
                                        <td
                                            colSpan={7}
                                            className="px-6 py-16 text-center text-muted-foreground"
                                        >
                                            <div className="flex flex-col items-center justify-center gap-3">
                                                <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-emerald-500/10 to-teal-500/10">
                                                    <EyeOff className="size-8 text-emerald-400/60" />
                                                </div>
                                                <p className="text-base font-bold text-foreground">
                                                    {t(
                                                        'products.no_products_found',
                                                    )}
                                                </p>
                                                <p className="max-w-[280px] text-xs">
                                                    {t(
                                                        'products.adjust_params',
                                                    )}
                                                </p>
                                            </div>
                                        </td>
                                    </motion.tr>
                                )}
                            </motion.tbody>
                        </table>
                    </div>

                    {/* Pagination */}
                    {lastPage > 1 && (
                        <div className="flex items-center justify-between border-t border-border bg-gradient-to-r from-neutral-900/5 to-transparent px-6 py-4 dark:from-neutral-100/5 dark:to-transparent">
                            <span className="text-xs text-muted-foreground">
                                {t('common.page')}{' '}
                                <span className="font-bold text-foreground">
                                    {currentPage}
                                </span>{' '}
                                {t('common.of')}{' '}
                                <span className="font-bold text-foreground">
                                    {lastPage}
                                </span>
                            </span>
                            <div className="flex gap-1">
                                {paginationLinks.map(
                                    (link: any, idx: number) => {
                                        if (!link.url) {
                                            return null;
                                        }

                                        return (
                                            <Link
                                                key={idx}
                                                href={link.url}
                                                className={`flex items-center justify-center rounded-lg px-3 py-1.5 text-xs font-medium transition-all duration-200 ${link.active ? 'bg-gradient-to-r from-emerald-600 to-teal-600 text-white shadow-md shadow-emerald-500/20' : 'border border-border bg-card text-muted-foreground hover:border-emerald-500/30 hover:bg-emerald-500/5 hover:text-foreground'}`}
                                                dangerouslySetInnerHTML={{
                                                    __html: link.label,
                                                }}
                                            />
                                        );
                                    },
                                )}
                            </div>
                        </div>
                    )}
                </motion.div>
            </motion.div>
        </>
    );
}

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