import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { Link, router } from '@inertiajs/react';
import axios from 'axios';
import { Boxes, ChevronDown, ChevronUp, Loader2, Search, Sparkles, Trash2, TriangleAlert, X } from 'lucide-react';
import React, { useState } from 'react';
import { getLevel } from '../pedidos/shared';
import { productEditUrl } from './filters';
import { ExpandField, fmtUtc, LEVEL_CONFIG, TruncCell } from './OrdersTable';

// Mesmo visual/ações da OrdersTable, com os campos de produto.

const iconBtn = 'w-7 h-7 flex items-center justify-center rounded-lg border border-border hover:bg-muted transition-colors';

function fmtMoney(value?: string | number | null) {
    if (value === null || value === undefined || value === '') return '—';
    const n = Number(value);
    if (isNaN(n)) return String(value);
    return n.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
}

function fmtNumber(value?: string | number | null) {
    if (value === null || value === undefined || value === '') return '—';
    const n = Number(value);
    return isNaN(n) ? String(value) : n.toLocaleString('pt-BR');
}

// 14 dígitos -> 00.000.000/0000-00; outro formato fica como veio
function fmtCnpj(value?: string | null) {
    if (!value) return '—';
    const digits = value.replace(/\D/g, '');
    return digits.length === 14 ? digits.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/, '$1.$2.$3/$4-$5') : value;
}

// "AAAA-MM-DD HH:MM:SS" -> "DD/MM/AAAA"
function fmtDate(value?: string | null) {
    if (!value) return '—';
    const [y, m, d] = String(value).slice(0, 10).split('-');
    return d && m && y ? `${d}/${m}/${y}` : String(value);
}

const sumBy = (rows: any[], key: string) => rows.reduce((acc, row) => acc + (Number(row[key]) || 0), 0);

export function ProductsTable({ products, integrationName }: { products: any[]; integrationName: string }) {
    const [expanded, setExpanded] = useState<Set<number>>(new Set());
    const [notifProduct, setNotifProduct] = useState<any>(null);
    const [stockProduct, setStockProduct] = useState<any>(null);
    // exclusão: produto escolhido, contagem do que vai junto (delete-preview) e estado do envio
    const [deleteProduct, setDeleteProduct] = useState<any>(null);
    const [deletePreview, setDeletePreview] = useState<any>(null);
    const [deleteError, setDeleteError] = useState<string | null>(null);
    const [deleting, setDeleting] = useState(false);

    const openDelete = (product: any) => {
        setDeleteProduct(product);
        setDeletePreview(null);
        setDeleteError(null);
        axios
            .get(`/produtos/${product.id}/delete-preview`)
            .then((res) => setDeletePreview(res.data))
            .catch(() => setDeleteError('Não foi possível carregar o que será excluído.'));
    };

    const closeDelete = () => {
        if (deleting) return;
        setDeleteProduct(null);
    };

    const confirmDelete = () => {
        if (!deleteProduct) return;
        setDeleting(true);
        router.delete(`/produtos/${deleteProduct.id}`, {
            preserveScroll: true,
            onSuccess: () => setDeleteProduct(null),
            onError: () => setDeleteError('Erro ao excluir o produto.'),
            onFinish: () => setDeleting(false),
        });
    };

    const toggleRow = (id: number) =>
        setExpanded((prev) => {
            const next = new Set(prev);
            next.has(id) ? next.delete(id) : next.add(id);
            return next;
        });

    const laura = (message: string) => window.dispatchEvent(new CustomEvent('laura:send-message', { detail: { message } }));

    const explainProduct = (product: any) => {
        const parts = [
            `Explique a situação deste produto:`,
            `integração="${integrationName}" fluxo="${product.flow_name ?? ''}" atividade="${product.activity_name ?? ''}"`,
            `id=${product.id} sku=${product.sku}${product.ean ? ` ean=${product.ean}` : ''} estoque=${product.stock ?? ''}`,
        ];
        if (product.notification) parts.push(`notificação="${product.notification}"`);
        laura(parts.join('\n'));
    };

    const formatNotification = () => {
        const text = `Formate esta notificação de integração:\n\nMensagem: ${notifProduct.notification}\nPayload: ${notifProduct.payload ?? ''}`;
        setNotifProduct(null);
        laura(text);
    };

    const cols = ['Fluxo', 'SKU', 'Nome', 'EAN', 'Estoque', 'Preço', 'Atividade Atual', 'Atualizado', 'Ações'];
    const level = notifProduct ? LEVEL_CONFIG[getLevel(notifProduct)] : undefined;

    return (
        <>
            <div className="overflow-x-auto rounded-xl border border-border bg-card">
                <Table>
                    <TableHeader>
                        <TableRow className="bg-muted/50 hover:bg-muted/50">
                            {cols.map((h) => (
                                <TableHead key={h} className="h-10 text-[10px] font-semibold tracking-widest whitespace-nowrap text-muted-foreground uppercase">
                                    {h}
                                </TableHead>
                            ))}
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {products.length === 0 && (
                            <TableRow>
                                <TableCell colSpan={cols.length} className="py-14 text-center text-xs text-muted-foreground">
                                    Nenhum produto encontrado.
                                </TableCell>
                            </TableRow>
                        )}
                        {products.map((product) => (
                            <React.Fragment key={product.id}>
                                <TableRow className="transition-colors hover:bg-muted/30">
                                    <TableCell className="py-2.5">
                                        <span className="text-xs text-muted-foreground">{product.flow_name ?? '—'}</span>
                                    </TableCell>
                                    <TableCell className="py-2.5">
                                        <TruncCell value={product.sku} max={20} />
                                    </TableCell>
                                    <TableCell className="max-w-[280px] py-2.5">
                                        {product.name ? (
                                            <Tooltip>
                                                <TooltipTrigger asChild>
                                                    <span className="block cursor-default truncate text-xs text-foreground">{product.name}</span>
                                                </TooltipTrigger>
                                                <TooltipContent>{product.name}</TooltipContent>
                                            </Tooltip>
                                        ) : (
                                            <span className="text-xs text-muted-foreground">—</span>
                                        )}
                                    </TableCell>
                                    <TableCell className="py-2.5">
                                        <TruncCell value={product.ean} max={15} />
                                    </TableCell>
                                    <TableCell className="py-2.5 text-xs text-foreground">
                                        {product.stocks?.length ? (
                                            <button
                                                type="button"
                                                onClick={() => setStockProduct(product)}
                                                className="inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 hover:bg-muted"
                                                title="Ver entradas de estoque"
                                            >
                                                <Boxes size={12} className="text-muted-foreground" />
                                                <span className="font-semibold">{fmtNumber(sumBy(product.stocks, 'quantity'))}</span>
                                                {product.stocks.length > 1 && (
                                                    <span className="rounded-full bg-muted px-1.5 text-[10px] text-muted-foreground">{product.stocks.length}</span>
                                                )}
                                            </button>
                                        ) : (
                                            product.stock ?? <span className="text-muted-foreground">—</span>
                                        )}
                                    </TableCell>
                                    <TableCell className="py-2.5 text-xs whitespace-nowrap text-foreground">{fmtMoney(product.price)}</TableCell>
                                    <TableCell className="py-2.5">
                                        {product.activity_name ? (
                                            <span className="rounded bg-blue-100 px-3 py-1 text-xs whitespace-nowrap text-blue-800 dark:bg-blue-900 dark:text-blue-100">
                                                {product.activity_name}
                                            </span>
                                        ) : (
                                            <span className="text-xs text-muted-foreground">—</span>
                                        )}
                                    </TableCell>
                                    <TableCell className="py-2.5 text-xs whitespace-nowrap text-muted-foreground">{fmtUtc(product.updated_at)}</TableCell>
                                    <TableCell className="py-2.5">
                                        <div className="flex items-center gap-1.5">
                                            <Tooltip>
                                                <TooltipTrigger asChild>
                                                    <Link href={productEditUrl(product.id)} className={`${iconBtn} text-muted-foreground hover:text-foreground`}>
                                                        <Search size={12} strokeWidth={2} />
                                                    </Link>
                                                </TooltipTrigger>
                                                <TooltipContent>Ver detalhes</TooltipContent>
                                            </Tooltip>

                                            <Tooltip>
                                                <TooltipTrigger asChild>
                                                    <button type="button" onClick={() => explainProduct(product)} className={`${iconBtn} text-amber-500`}>
                                                        <Sparkles size={12} strokeWidth={2} />
                                                    </button>
                                                </TooltipTrigger>
                                                <TooltipContent>Explicar com Laura</TooltipContent>
                                            </Tooltip>

                                            {product.notification ? (
                                                <Tooltip>
                                                    <TooltipTrigger asChild>
                                                        <button type="button" onClick={() => setNotifProduct(product)} className={iconBtn}>
                                                            <TriangleAlert size={12} className={LEVEL_CONFIG[getLevel(product)]?.bg ?? 'text-rose-500'} />
                                                        </button>
                                                    </TooltipTrigger>
                                                    <TooltipContent>{LEVEL_CONFIG[getLevel(product)]?.label ?? 'Notificação'} — clique para ver</TooltipContent>
                                                </Tooltip>
                                            ) : (
                                                <div className="pointer-events-none h-7 w-7 opacity-0" />
                                            )}

                                            <Tooltip>
                                                <TooltipTrigger asChild>
                                                    <button
                                                        type="button"
                                                        onClick={() => toggleRow(product.id)}
                                                        className={`${iconBtn} text-muted-foreground hover:text-foreground`}
                                                    >
                                                        {expanded.has(product.id) ? <ChevronUp size={12} strokeWidth={2} /> : <ChevronDown size={12} strokeWidth={2} />}
                                                    </button>
                                                </TooltipTrigger>
                                                <TooltipContent>{expanded.has(product.id) ? 'Fechar' : 'Abrir'}</TooltipContent>
                                            </Tooltip>

                                            <Tooltip>
                                                <TooltipTrigger asChild>
                                                    <button
                                                        type="button"
                                                        onClick={() => openDelete(product)}
                                                        className={`${iconBtn} text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-950`}
                                                    >
                                                        <Trash2 size={12} strokeWidth={2} />
                                                    </button>
                                                </TooltipTrigger>
                                                <TooltipContent>Excluir produto</TooltipContent>
                                            </Tooltip>
                                        </div>
                                    </TableCell>
                                </TableRow>

                                {expanded.has(product.id) && (
                                    <TableRow className="bg-muted/20 hover:bg-muted/20">
                                        <TableCell colSpan={cols.length} className="px-6 py-4">
                                            <div className="grid grid-cols-2 gap-x-8 gap-y-4 sm:grid-cols-3">
                                                <ExpandField label="NCM" value={product.product_ncm} />
                                                <ExpandField label="Preço Especial" value={product.special_price ? fmtMoney(product.special_price) : null} />
                                                <ExpandField label="Peso" value={product.weight} />
                                                <ExpandField label="Fabricante" value={product.manufacturer} />
                                                <ExpandField label="Status" value={product.status} />
                                                <ExpandField label="Criado em" value={product.created_at ? fmtUtc(product.created_at) : null} />
                                            </div>
                                        </TableCell>
                                    </TableRow>
                                )}
                            </React.Fragment>
                        ))}
                    </TableBody>
                </Table>
            </div>

            {/* ── Modal estoque (uma ou mais entradas de stocks) ── */}
            {stockProduct && (
                <div
                    className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
                    onClick={(e) => {
                        if (e.target === e.currentTarget) setStockProduct(null);
                    }}
                >
                    <div className="flex max-h-[90vh] w-full max-w-4xl flex-col overflow-hidden rounded-2xl border border-border bg-card shadow-xl">
                        <div className="flex items-start justify-between gap-3 border-b border-border px-5 py-4">
                            <div className="min-w-0">
                                <p className="text-sm font-semibold text-foreground">Estoque — {stockProduct.sku}</p>
                                <p className="truncate text-xs text-muted-foreground">
                                    {stockProduct.name}
                                    {stockProduct.ean ? ` · EAN ${stockProduct.ean}` : ''}
                                </p>
                            </div>
                            <button
                                type="button"
                                onClick={() => setStockProduct(null)}
                                className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border text-muted-foreground hover:bg-muted"
                            >
                                <X size={14} strokeWidth={2} />
                            </button>
                        </div>

                        <div className="grid grid-cols-2 gap-3 border-b border-border px-5 py-4 sm:grid-cols-4">
                            {[
                                { label: 'Entradas', value: stockProduct.stocks.length },
                                { label: 'Quantidade', value: fmtNumber(sumBy(stockProduct.stocks, 'quantity')) },
                                { label: 'Faturada', value: fmtNumber(sumBy(stockProduct.stocks, 'invoiced_quantity')) },
                                { label: 'Avariada', value: fmtNumber(sumBy(stockProduct.stocks, 'damaged_quantity')) },
                            ].map((stat) => (
                                <div key={stat.label} className="rounded-xl border border-border bg-background px-3 py-2">
                                    <p className="text-[10px] font-semibold tracking-widest text-muted-foreground uppercase">{stat.label}</p>
                                    <p className="mt-0.5 text-base font-semibold text-foreground">{stat.value}</p>
                                </div>
                            ))}
                        </div>

                        <div className="overflow-auto px-5 py-4">
                            <div className="overflow-x-auto rounded-lg border border-border">
                                <Table>
                                    <TableHeader>
                                        <TableRow className="bg-muted/50 hover:bg-muted/50">
                                            {['CNPJ depositante', 'Lote', 'Filial', 'Quantidade', 'Faturada', 'Avariada', 'Validade', 'Atualizado'].map((h) => (
                                                <TableHead key={h} className="h-9 text-[10px] font-semibold tracking-widest whitespace-nowrap text-muted-foreground uppercase">
                                                    {h}
                                                </TableHead>
                                            ))}
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {stockProduct.stocks.map((stock: any) => (
                                            <TableRow key={stock.id} className="hover:bg-muted/30">
                                                <TableCell className="py-2 font-mono text-xs whitespace-nowrap">{fmtCnpj(stock.depositor_cnpj)}</TableCell>
                                                <TableCell className="py-2 text-xs">{stock.batch || '—'}</TableCell>
                                                <TableCell className="py-2 text-xs">{stock.subsidiary || '—'}</TableCell>
                                                <TableCell className="py-2 text-xs font-semibold">{fmtNumber(stock.quantity)}</TableCell>
                                                <TableCell className="py-2 text-xs">{fmtNumber(stock.invoiced_quantity)}</TableCell>
                                                <TableCell className="py-2 text-xs">{fmtNumber(stock.damaged_quantity)}</TableCell>
                                                <TableCell className="py-2 text-xs whitespace-nowrap">{fmtDate(stock.expiration_date)}</TableCell>
                                                <TableCell className="py-2 text-xs whitespace-nowrap text-muted-foreground">{fmtUtc(stock.updated_at)}</TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            </div>
                            {stockProduct.stock !== null && stockProduct.stock !== undefined && String(stockProduct.stock) !== String(sumBy(stockProduct.stocks, 'quantity')) && (
                                <p className="mt-3 text-[11px] text-muted-foreground">
                                    Estoque total gravado no produto: <strong className="text-foreground">{fmtNumber(stockProduct.stock)}</strong> (diferente da soma das entradas).
                                </p>
                            )}
                        </div>
                    </div>
                </div>
            )}

            {/* ── Modal exclusão ── */}
            {deleteProduct && (
                <div
                    className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
                    onClick={(e) => {
                        if (e.target === e.currentTarget) closeDelete();
                    }}
                >
                    <div className="w-full max-w-md overflow-hidden rounded-2xl border border-border bg-card shadow-xl">
                        <div className="flex items-start justify-between gap-3 border-b border-border px-5 py-4">
                            <div className="min-w-0">
                                <p className="text-sm font-semibold text-foreground">Excluir produto — {deleteProduct.sku}</p>
                                <p className="truncate text-xs text-muted-foreground">{deleteProduct.name}</p>
                            </div>
                            <button
                                type="button"
                                onClick={closeDelete}
                                className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-border text-muted-foreground hover:bg-muted"
                            >
                                <X size={14} strokeWidth={2} />
                            </button>
                        </div>

                        <div className="space-y-3 px-5 py-4 text-xs">
                            {!deletePreview && !deleteError && (
                                <p className="inline-flex items-center gap-2 text-muted-foreground">
                                    <Loader2 size={12} className="animate-spin" /> Verificando o que será excluído...
                                </p>
                            )}
                            {deletePreview && (
                                <>
                                    <p className="text-foreground">Serão excluídos permanentemente:</p>
                                    <ul className="space-y-1 rounded-lg border border-border bg-background px-3 py-2 text-muted-foreground">
                                        <li>O produto <strong className="text-foreground">{deleteProduct.sku}</strong></li>
                                        {[
                                            ['children', 'produto(s) filho(s), com as subtabelas deles'],
                                            ['stocks', 'entrada(s) de estoque'],
                                            ['variations', 'variação(ões)'],
                                            ['images', 'imagem(ns)'],
                                            ['notifications', 'notificação(ões)'],
                                        ]
                                            .filter(([key]) => deletePreview.counts[key] > 0)
                                            .map(([key, label]) => (
                                                <li key={key}>
                                                    <strong className="text-foreground">{deletePreview.counts[key]}</strong> {label}
                                                </li>
                                            ))}
                                    </ul>
                                    <p className="text-rose-600 dark:text-rose-400">Essa ação não pode ser desfeita.</p>
                                </>
                            )}
                            {deleteError && <p className="text-rose-600 dark:text-rose-400">{deleteError}</p>}
                        </div>

                        <div className="flex flex-col-reverse gap-2 border-t border-border px-5 py-3 sm:flex-row sm:justify-end">
                            <button
                                type="button"
                                onClick={closeDelete}
                                disabled={deleting}
                                className="rounded-md border border-border px-4 py-2 text-xs font-medium hover:bg-muted disabled:opacity-50"
                            >
                                Cancelar
                            </button>
                            <button
                                type="button"
                                onClick={confirmDelete}
                                disabled={!deletePreview || deleting}
                                className="inline-flex items-center justify-center gap-2 rounded-md bg-rose-600 px-4 py-2 text-xs font-medium text-white hover:bg-rose-700 disabled:opacity-50"
                            >
                                {deleting ? <Loader2 size={12} className="animate-spin" /> : <Trash2 size={12} />}
                                Excluir
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* ── Modal notificação ── */}
            {notifProduct && (
                <div
                    className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
                    onClick={(e) => {
                        if (e.target === e.currentTarget) setNotifProduct(null);
                    }}
                >
                    <div className="w-full max-w-lg overflow-hidden rounded-2xl border border-border bg-card shadow-xl">
                        <div className="flex items-center justify-between border-b border-border px-5 py-4">
                            <div>
                                <p className="text-sm font-semibold text-foreground">Notificação — {notifProduct.sku}</p>
                                {level && <span className={`text-[10px] font-bold ${level.color}`}>{level.label}</span>}
                            </div>
                            <div className="flex items-center gap-2">
                                <Tooltip>
                                    <TooltipTrigger asChild>
                                        <button type="button" onClick={formatNotification} className="flex h-8 w-8 items-center justify-center rounded-lg border border-border hover:bg-muted">
                                            <Sparkles size={14} className="text-amber-400" />
                                        </button>
                                    </TooltipTrigger>
                                    <TooltipContent>Formatar com Laura</TooltipContent>
                                </Tooltip>
                                <button
                                    type="button"
                                    onClick={() => setNotifProduct(null)}
                                    className="flex h-8 w-8 items-center justify-center rounded-lg border border-border text-muted-foreground hover:bg-muted"
                                >
                                    <X size={14} strokeWidth={2} />
                                </button>
                            </div>
                        </div>

                        <div className="flex max-h-96 flex-col gap-3 overflow-y-auto px-5 py-4">
                            {notifProduct.class && <ExpandField label="Classe" value={notifProduct.class} />}
                            {notifProduct.notification && <ExpandField label="Mensagem" value={notifProduct.notification} />}
                            {notifProduct.payload && <ExpandField label="Payload" value={notifProduct.payload} />}
                        </div>
                    </div>
                </div>
            )}
        </>
    );
}
