import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { cn } from '@/lib/utils';
import { Link } from '@inertiajs/react';
import { Bell, ChevronDown, ChevronUp, CircleCheck, Send, TriangleAlert } from 'lucide-react';
import React, { useState } from 'react';
import { orderEditUrl } from './filters';
import { fmtUtc, LEVEL_CONFIG } from './OrdersTable';

// Notificações da integração para o usuário logado (seção "Notificações" de integracoes/Show).

function LevelBadge({ level }: { level: number }) {
    const cfg = LEVEL_CONFIG[level];
    return (
        <span className={cn('inline-flex items-center gap-1 text-[11px] font-semibold whitespace-nowrap', cfg?.color ?? 'text-muted-foreground')}>
            <TriangleAlert size={12} className={cfg?.bg} />
            {cfg?.label ?? `Nível ${level}`}
        </span>
    );
}

function Field({ label, value, mono }: { label: string; value?: React.ReactNode; mono?: boolean }) {
    return (
        <div>
            <p className="mb-0.5 text-[10px] font-semibold tracking-widest text-muted-foreground uppercase">{label}</p>
            <div className={cn('text-xs break-all whitespace-pre-wrap text-foreground', { 'font-mono': mono })}>
                {value || <span className="text-muted-foreground">—</span>}
            </div>
        </div>
    );
}

function prettyPayload(raw?: string | null) {
    if (!raw) return null;
    try {
        return JSON.stringify(JSON.parse(raw), null, 2);
    } catch {
        return raw;
    }
}

function EntityRef({ n }: { n: any }) {
    if (n.entity_type === 'orders' && n.entity_id) {
        return (
            <Link href={orderEditUrl(n.entity_id)} className="font-mono text-xs text-foreground underline-offset-2 hover:underline" onClick={(e) => e.stopPropagation()}>
                {n.increment_id ?? n.order_id ?? `#${n.entity_id}`}
            </Link>
        );
    }
    if (n.entity_type === 'products' && n.entity_id) {
        return (
            <Link href={route('produtos.edit', n.entity_id)} className="font-mono text-xs text-foreground underline-offset-2 hover:underline" onClick={(e) => e.stopPropagation()}>
                {n.sku ?? `#${n.entity_id}`}
            </Link>
        );
    }
    return <span className="text-xs text-muted-foreground">—</span>;
}

export function NotificationsSection({ items }: { items: any[] }) {
    const [expanded, setExpanded] = useState<Set<number>>(new Set());
    const toggle = (id: number) =>
        setExpanded((prev) => {
            const next = new Set(prev);
            next.has(id) ? next.delete(id) : next.add(id);
            return next;
        });

    const cols = ['Nível', 'Mensagem', 'Referência', 'Status', 'Data', ''];

    return (
        <div className="space-y-4">
            <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, i) => (
                                <TableHead key={i} className="h-10 text-[10px] font-semibold tracking-widest whitespace-nowrap text-muted-foreground uppercase">
                                    {h}
                                </TableHead>
                            ))}
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        {items.length === 0 && (
                            <TableRow>
                                <TableCell colSpan={cols.length} className="py-14 text-center text-xs text-muted-foreground">
                                    <Bell size={20} strokeWidth={1.5} className="mx-auto mb-2 opacity-40" />
                                    Nenhuma notificação desta integração.
                                </TableCell>
                            </TableRow>
                        )}
                        {items.map((n) => {
                            const open = expanded.has(n.id);
                            return (
                                <React.Fragment key={n.id}>
                                    <TableRow className="cursor-pointer transition-colors hover:bg-muted/30" onClick={() => toggle(n.id)}>
                                        <TableCell className="py-3 align-top">
                                            <LevelBadge level={Number(n.level)} />
                                        </TableCell>
                                        <TableCell className="max-w-[420px] py-3 align-top">
                                            <p className={cn('text-xs text-foreground', { 'line-clamp-2': !open })}>{n.notification}</p>
                                            {(n.type || n.activity_name) && (
                                                <p className="mt-1 text-[11px] text-muted-foreground">{[n.type, n.activity_name].filter(Boolean).join(' · ')}</p>
                                            )}
                                        </TableCell>
                                        <TableCell className="py-3 align-top">
                                            <EntityRef n={n} />
                                        </TableCell>
                                        <TableCell className="py-3 align-top">
                                            <div className="flex flex-col gap-1 text-[11px] whitespace-nowrap">
                                                {Number(n.success) ? (
                                                    <span className="inline-flex items-center gap-1 font-medium text-emerald-700 dark:text-emerald-400">
                                                        <CircleCheck size={12} /> Resolvida
                                                    </span>
                                                ) : (
                                                    <span className="inline-flex items-center gap-1 font-medium text-amber-700 dark:text-amber-400">
                                                        <TriangleAlert size={12} /> Em aberto
                                                    </span>
                                                )}
                                                {!!Number(n.processed) && (
                                                    <span className="inline-flex items-center gap-1 text-muted-foreground">
                                                        <Send size={11} /> Enviada
                                                    </span>
                                                )}
                                            </div>
                                        </TableCell>
                                        <TableCell className="py-3 align-top text-xs whitespace-nowrap text-muted-foreground">{fmtUtc(n.created_at)}</TableCell>
                                        <TableCell className="w-8 py-3 align-top text-muted-foreground">{open ? <ChevronUp size={14} /> : <ChevronDown size={14} />}</TableCell>
                                    </TableRow>
                                    {open && (
                                        <TableRow className="bg-muted/20 hover:bg-muted/20">
                                            <TableCell colSpan={cols.length} className="px-6 py-4">
                                                <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
                                                    <Field label="Classe" value={n.class} mono />
                                                    <Field label="Origem" value={n.origin} />
                                                    <Field label="Atualizada em" value={fmtUtc(n.updated_at)} />
                                                    <div className="md:col-span-3">
                                                        <Field label="Payload" value={prettyPayload(n.payload)} mono />
                                                    </div>
                                                </div>
                                            </TableCell>
                                        </TableRow>
                                    )}
                                </React.Fragment>
                            );
                        })}
                    </TableBody>
                </Table>
            </div>
        </div>
    );
}
