import { cn } from '@/lib/utils';
import { Link } from '@inertiajs/react';
import {
    ArrowDownRight, ArrowRight, ArrowUpRight, Box, CircleCheck, Clock, Minus, Pause, Play, Plug, RefreshCw, ShoppingCart, Timer, TriangleAlert, Webhook,
    Workflow, type LucideIcon,
} from 'lucide-react';
import { useState, type ReactNode } from 'react';
import { orderEditUrl } from './filters';

// Visão geral da integração. Uma série só (pedidos) → uma cor: blue-500,
// validada contra as superfícies clara e escura. Texto sempre em tokens de texto.

type Overview = {
    orders_today: number;
    orders_yesterday: number;
    orders_30d: number;
    orders_total: number;
    orders_delayed: number;
    products_total: number;
    webhooks_pending: number;
    last_order_at: string | null;
    last_webhook_at: string | null;
    orders_per_day: { date: string; total: number }[];
    orders_by_activity: { id: number | null; name: string | null; color: string | null; total: number }[];
    orders_by_activity_other: number;
    flows: { flows: number; active: number; paused: number; connections: number };
    recent_orders: { id: number; increment_id: string | null; order_id: string | null; activity_name: string | null; activity_color: string | null; updated_at: string }[];
    cached_at: string;
};

const nf = (n: number) => n.toLocaleString('pt-BR');

// Datas do banco em UTC.
function parseUtc(value: string) {
    return new Date(value.replace(' ', 'T').replace(/Z?$/, 'Z'));
}

function timeAgo(value?: string | null) {
    if (!value) return 'nunca';
    const diff = (Date.now() - parseUtc(value).getTime()) / 1000;
    if (isNaN(diff)) return '—';
    if (diff < 60) return 'agora mesmo';
    const units: [number, string, string][] = [
        [60, 'min', 'min'],
        [3600, 'hora', 'horas'],
        [86400, 'dia', 'dias'],
        [2592000, 'mês', 'meses'],
        [31536000, 'ano', 'anos'],
    ];
    let pick = units[0];
    for (const u of units) if (diff >= u[0]) pick = u;
    const n = Math.floor(diff / pick[0]);
    return `há ${n} ${n === 1 ? pick[1] : pick[2]}`;
}

// "2026-09-28" → "28/09" (data local, sem conversão de fuso: já vem no dia de Brasília)
const dayLabel = (d: string) => `${d.slice(8, 10)}/${d.slice(5, 7)}`;
const weekday = (d: string) => new Date(`${d}T12:00:00`).toLocaleDateString('pt-BR', { weekday: 'short' }).replace('.', '');

function Card({ title, action, children, className }: { title?: ReactNode; action?: ReactNode; children: ReactNode; className?: string }) {
    return (
        <div className={cn('flex flex-col rounded-xl border border-border bg-card p-5', className)}>
            {(title || action) && (
                <div className="mb-4 flex items-center justify-between gap-3">
                    {title && <h4 className="text-sm font-semibold">{title}</h4>}
                    {action}
                </div>
            )}
            <div className="flex flex-1 flex-col">{children}</div>
        </div>
    );
}

function Kpi({ icon: Icon, label, value, children }: { icon: LucideIcon; label: string; value: ReactNode; children?: ReactNode }) {
    return (
        <div className="flex flex-col gap-3 rounded-xl border border-border bg-card p-5">
            <div className="flex items-center justify-between">
                <span className="text-xs font-medium text-muted-foreground">{label}</span>
                <span className="flex h-8 w-8 items-center justify-center rounded-lg bg-muted text-muted-foreground">
                    <Icon size={15} strokeWidth={2} />
                </span>
            </div>
            <p className="text-3xl font-semibold tracking-tight tabular-nums">{value}</p>
            {children && <div className="text-xs text-muted-foreground">{children}</div>}
        </div>
    );
}

function Delta({ today, yesterday }: { today: number; yesterday: number }) {
    const diff = today - yesterday;
    const Icon = diff > 0 ? ArrowUpRight : diff < 0 ? ArrowDownRight : Minus;
    return (
        <span className="inline-flex items-center gap-1">
            <Icon size={13} className="text-foreground" />
            <span>
                {diff === 0 ? 'igual a ontem' : `${diff > 0 ? '+' : ''}${nf(diff)} vs. ontem`} ({nf(yesterday)})
            </span>
        </span>
    );
}

// ── gráfico: pedidos por dia ─────────────────────────────────────────────────

function OrdersPerDayChart({ days }: { days: Overview['orders_per_day'] }) {
    const [hover, setHover] = useState<number | null>(null);
    const max = Math.max(...days.map((d) => d.total), 0);
    const total = days.reduce((s, d) => s + d.total, 0);
    const lastIndex = days.length - 1;

    if (total === 0) {
        return (
            <div className="flex min-h-44 flex-1 flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-border text-muted-foreground">
                <ShoppingCart size={20} strokeWidth={1.5} className="opacity-50" />
                <p className="text-xs">Nenhum pedido nos últimos 14 dias.</p>
            </div>
        );
    }

    return (
        <div className="flex flex-1 flex-col">
            <div
                className="relative min-h-44 flex-1"
                role="img"
                aria-label={`Pedidos por dia nos últimos 14 dias: ${days.map((d) => `${dayLabel(d.date)} ${d.total}`).join(', ')}`}
            >
                {/* grade recessiva: topo (máximo) e base */}
                <div className="pointer-events-none absolute inset-x-0 top-0 flex items-center gap-2">
                    <span className="text-[10px] text-muted-foreground tabular-nums">{nf(max)}</span>
                    <div className="h-px flex-1 border-t border-dashed border-border" />
                </div>
                <div className="pointer-events-none absolute inset-x-0 bottom-0 h-px bg-border" />

                <div className="absolute inset-x-0 top-5 bottom-0 flex items-end gap-[2px] pl-6">
                    {days.map((d, i) => {
                        const pct = max ? (d.total / max) * 100 : 0;
                        const active = hover === i;
                        return (
                            <div
                                key={d.date}
                                className="relative flex h-full flex-1 cursor-default items-end justify-center"
                                onMouseEnter={() => setHover(i)}
                                onMouseLeave={() => setHover(null)}
                            >
                                {active && <div className="absolute inset-0 rounded-md bg-muted/60" />}
                                <div
                                    className={cn('relative w-full max-w-6 rounded-t-[4px] bg-blue-500 transition-opacity', {
                                        'opacity-60': hover !== null && !active,
                                    })}
                                    style={{ height: d.total ? `max(${pct}%, 3px)` : 0 }}
                                />
                                {active && (
                                    <div
                                        className={cn(
                                            'absolute bottom-full z-10 mb-1 rounded-lg border border-border bg-popover px-2.5 py-1.5 text-xs whitespace-nowrap shadow-md',
                                            i > lastIndex - 3 ? 'right-0' : i < 3 ? 'left-0' : 'left-1/2 -translate-x-1/2',
                                        )}
                                    >
                                        <p className="text-muted-foreground capitalize">
                                            {i === lastIndex ? 'Hoje' : weekday(d.date)}, {dayLabel(d.date)}
                                        </p>
                                        <p className="font-semibold tabular-nums">
                                            {nf(d.total)} pedido{d.total !== 1 ? 's' : ''}
                                        </p>
                                    </div>
                                )}
                            </div>
                        );
                    })}
                </div>
            </div>

            {/* eixo x: um rótulo a cada 2 dias + hoje */}
            <div className="mt-2 flex gap-[2px] pl-6">
                {days.map((d, i) => (
                    <span key={d.date} className="flex-1 text-center text-[10px] text-muted-foreground tabular-nums">
                        {i === lastIndex ? 'Hoje' : (lastIndex - i) % 2 === 0 ? dayLabel(d.date) : ''}
                    </span>
                ))}
            </div>
        </div>
    );
}

// ── pedidos por atividade ────────────────────────────────────────────────────

function ActivityBreakdown({ rows, other }: { rows: Overview['orders_by_activity']; other: number }) {
    const all = [...rows.map((r) => ({ ...r, label: r.name ?? 'Sem atividade' })), ...(other > 0 ? [{ id: -1, label: 'Outras', color: null, total: other, name: null }] : [])];
    const max = Math.max(...all.map((r) => r.total), 0);

    if (all.length === 0) {
        return <p className="py-10 text-center text-xs text-muted-foreground">Nenhum pedido nos últimos 30 dias.</p>;
    }

    return (
        <ul className="space-y-3">
            {all.map((r) => (
                <li key={r.id ?? 'null'} className="group">
                    <div className="mb-1 flex items-center justify-between gap-3 text-xs">
                        <span className="flex min-w-0 items-center gap-2">
                            <span
                                className="h-2.5 w-2.5 flex-shrink-0 rounded-full border border-border"
                                style={{ backgroundColor: r.color ?? 'transparent' }}
                                aria-hidden
                            />
                            <span className="truncate text-foreground" title={r.label}>
                                {r.label}
                            </span>
                        </span>
                        <span className="font-semibold tabular-nums">{nf(r.total)}</span>
                    </div>
                    <div className="h-2 rounded-full bg-muted">
                        <div className="h-2 rounded-full bg-blue-500 transition-all" style={{ width: `${max ? (r.total / max) * 100 : 0}%` }} />
                    </div>
                </li>
            ))}
        </ul>
    );
}

// ── saúde dos fluxos ─────────────────────────────────────────────────────────

function FlowsHealth({ flows, lastOrderAt, lastWebhookAt, onGoToFlows }: { flows: Overview['flows']; lastOrderAt: string | null; lastWebhookAt: string | null; onGoToFlows: () => void }) {
    const totalActs = flows.active + flows.paused;
    const activePct = totalActs ? (flows.active / totalActs) * 100 : 0;

    return (
        <div className="flex flex-1 flex-col gap-5">
            <div className="grid grid-cols-2 gap-3">
                <div className="rounded-lg bg-muted/50 p-3">
                    <p className="flex items-center gap-1.5 text-xs text-muted-foreground">
                        <Workflow size={12} /> Fluxos
                    </p>
                    <p className="mt-1 text-xl font-semibold tabular-nums">{nf(flows.flows)}</p>
                </div>
                <div className="rounded-lg bg-muted/50 p-3">
                    <p className="flex items-center gap-1.5 text-xs text-muted-foreground">
                        <Plug size={12} /> Conexões
                    </p>
                    <p className="mt-1 text-xl font-semibold tabular-nums">{nf(flows.connections)}</p>
                </div>
            </div>

            <div>
                <div className="mb-2 flex items-center justify-between text-xs">
                    <span className="text-muted-foreground">Atividades</span>
                    <span className="tabular-nums">{nf(totalActs)}</span>
                </div>
                {totalActs > 0 ? (
                    <>
                        <div className="flex h-2 gap-[2px] overflow-hidden rounded-full">
                            {flows.active > 0 && <div className="h-full bg-emerald-500" style={{ width: `${activePct}%` }} />}
                            {flows.paused > 0 && <div className="h-full flex-1 bg-amber-400" />}
                        </div>
                        <div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs">
                            <span className="inline-flex items-center gap-1.5">
                                <Play size={11} className="text-emerald-600 dark:text-emerald-400" />
                                {nf(flows.active)} ativa{flows.active !== 1 ? 's' : ''}
                            </span>
                            <span className="inline-flex items-center gap-1.5">
                                <Pause size={11} className="text-amber-600 dark:text-amber-400" />
                                {nf(flows.paused)} pausada{flows.paused !== 1 ? 's' : ''}
                            </span>
                        </div>
                    </>
                ) : (
                    <p className="text-xs text-muted-foreground">Nenhuma atividade configurada.</p>
                )}
            </div>

            <div className="space-y-2 border-t border-border pt-4 text-xs">
                <p className="flex items-center justify-between gap-2">
                    <span className="inline-flex items-center gap-1.5 text-muted-foreground">
                        <ShoppingCart size={12} /> Último pedido
                    </span>
                    <span>{timeAgo(lastOrderAt)}</span>
                </p>
                <p className="flex items-center justify-between gap-2">
                    <span className="inline-flex items-center gap-1.5 text-muted-foreground">
                        <Webhook size={12} /> Último webhook
                    </span>
                    <span>{timeAgo(lastWebhookAt)}</span>
                </p>
            </div>

            <button
                type="button"
                onClick={onGoToFlows}
                className="mt-auto inline-flex items-center gap-1 self-start text-xs font-medium text-muted-foreground hover:text-foreground"
            >
                Ver fluxos <ArrowRight size={12} />
            </button>
        </div>
    );
}

// ── página ───────────────────────────────────────────────────────────────────

export function OverviewSection({
    data,
    onNavigate,
    onRefresh,
    refreshing,
}: {
    data: Overview;
    onNavigate: (section: string) => void;
    onRefresh: () => void;
    refreshing: boolean;
}) {
    const days14 = data.orders_per_day.reduce((s, d) => s + d.total, 0);

    return (
        <div className="space-y-4">
            {/* os números vêm de um cache de 2 min no servidor */}
            <div className="-mt-2 flex items-center justify-end gap-2 text-xs text-muted-foreground">
                <span>Atualizado {timeAgo(data.cached_at)}</span>
                <button
                    type="button"
                    onClick={onRefresh}
                    disabled={refreshing}
                    className="inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 font-medium hover:bg-muted hover:text-foreground disabled:opacity-50"
                >
                    <RefreshCw size={12} className={cn({ 'animate-spin': refreshing })} /> Atualizar
                </button>
            </div>

            {data.orders_delayed > 0 && (
                <div className="flex items-center gap-3 rounded-xl border border-violet-200 bg-violet-50 px-4 py-3 text-sm dark:border-violet-800 dark:bg-violet-950/50">
                    <Timer size={16} className="flex-shrink-0 text-violet-600 dark:text-violet-400" />
                    <span className="flex-1">
                        <strong>{nf(data.orders_delayed)}</strong> pedido{data.orders_delayed !== 1 ? 's' : ''} atrasado{data.orders_delayed !== 1 ? 's' : ''} na
                        atividade atual.
                    </span>
                    <button type="button" onClick={() => onNavigate('pedidos')} className="text-xs font-medium hover:underline">
                        Ver pedidos
                    </button>
                </div>
            )}

            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
                <Kpi icon={ShoppingCart} label="Pedidos hoje" value={nf(data.orders_today)}>
                    <Delta today={data.orders_today} yesterday={data.orders_yesterday} />
                </Kpi>
                <Kpi icon={Clock} label="Pedidos em 30 dias" value={nf(data.orders_30d)}>
                    {nf(data.orders_total)} no total
                </Kpi>
                <Kpi icon={Box} label="Produtos" value={nf(data.products_total)}>
                    cadastrados nesta integração
                </Kpi>
                <Kpi icon={Webhook} label="Webhooks pendentes" value={nf(data.webhooks_pending)}>
                    {data.webhooks_pending > 0 ? (
                        <span className="inline-flex items-center gap-1 font-medium text-amber-700 dark:text-amber-400">
                            <TriangleAlert size={12} /> Aguardando processamento
                        </span>
                    ) : (
                        <span className="inline-flex items-center gap-1 font-medium text-emerald-700 dark:text-emerald-400">
                            <CircleCheck size={12} /> Tudo processado
                        </span>
                    )}
                </Kpi>
            </div>

            <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
                <Card
                    className="xl:col-span-2"
                    title="Pedidos por dia"
                    action={
                        <span className="text-xs text-muted-foreground">
                            últimos 14 dias · <strong className="text-foreground tabular-nums">{nf(days14)}</strong> pedidos
                        </span>
                    }
                >
                    <OrdersPerDayChart days={data.orders_per_day} />
                </Card>

                <Card title="Saúde dos fluxos">
                    <FlowsHealth
                        flows={data.flows}
                        lastOrderAt={data.last_order_at}
                        lastWebhookAt={data.last_webhook_at}
                        onGoToFlows={() => onNavigate('fluxos')}
                    />
                </Card>
            </div>

            <div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
                <Card title="Onde estão os pedidos" action={<span className="text-xs text-muted-foreground">atividade atual · últimos 30 dias</span>}>
                    <ActivityBreakdown rows={data.orders_by_activity} other={data.orders_by_activity_other} />
                </Card>

                <Card
                    title="Últimos pedidos movimentados"
                    action={
                        <button type="button" onClick={() => onNavigate('pedidos')} className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground">
                            Ver todos <ArrowRight size={12} />
                        </button>
                    }
                >
                    {data.recent_orders.length > 0 ? (
                        <ul className="-mx-2 divide-y divide-border">
                            {data.recent_orders.map((o) => (
                                <li key={o.id}>
                                    <Link
                                        href={orderEditUrl(o.id)}
                                        className="flex items-center justify-between gap-3 rounded-lg px-2 py-2.5 transition-colors hover:bg-muted/50"
                                    >
                                        <span className="min-w-0">
                                            <span className="block font-mono text-xs font-medium">{o.increment_id ?? o.order_id ?? `#${o.id}`}</span>
                                            <span className="mt-0.5 flex items-center gap-1.5 text-xs text-muted-foreground">
                                                <span
                                                    className="h-2 w-2 flex-shrink-0 rounded-full border border-border"
                                                    style={{ backgroundColor: o.activity_color ?? 'transparent' }}
                                                    aria-hidden
                                                />
                                                <span className="truncate">{o.activity_name ?? 'Sem atividade'}</span>
                                            </span>
                                        </span>
                                        <span className="flex-shrink-0 text-xs text-muted-foreground">{timeAgo(o.updated_at)}</span>
                                    </Link>
                                </li>
                            ))}
                        </ul>
                    ) : (
                        <p className="py-10 text-center text-xs text-muted-foreground">Nenhum pedido ainda.</p>
                    )}
                </Card>
            </div>
        </div>
    );
}
