import { Head, Link, useForm } from '@inertiajs/react';
import { ExternalLink, Layers, Loader2, RefreshCw } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
import { ConfirmActionModal } from '@/components/confirm-action-modal';
import { JsonPaginatorFooter } from '@/components/json-paginator-footer';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Checkbox } from '@/components/ui/checkbox';
import { usePaginatedAuditSection } from '@/hooks/use-paginated-audit-section';
import { cn } from '@/lib/utils';

type InvestmentBalanceIssue = {
    investment_id: number;
    txid: string;
    status: string;
    is_admin_adjustment: boolean;
    investor_name: string;
    investor_email: string | null;
    stored_capital_usd: string;
    computed_capital_usd: string;
    capital_delta_usd: string;
    transaction_mismatches: Array<{
        transaction_id: number;
        stored_usd: string | null;
        expected_usd: string;
    }>;
};

type UserBalanceIssue = {
    user_id: number;
    name: string;
    email: string;
    reported_withdrawable_usd: string;
    sum_investment_withdrawable_usd: string;
    delta_usd: string;
};

type ManualBalanceCredit = {
    id: number;
    user_id: number | null | undefined;
    investor_name: string;
    investor_email: string | null;
    amount_usd: string;
    balance_after_usd: string;
    container_balance_usd: string;
    admin_note: string | null;
    created_at: string | null;
    created_by: string | null;
    can_revert: boolean;
};

type AccrualInconsistency = {
    transaction_id: number;
    investment_id: number;
    accrual_on: string;
    txid: string;
    is_imported: boolean;
    investor_name: string;
    investor_email: string | null;
    current_gain_usd: string | null;
    proposed_gain_usd: string | null;
    gain_delta_usd: string | null;
    current_period: string | null;
    proposed_period: string | null;
    current_period_label: string | null;
    proposed_period_label: string | null;
    accrual_run_url: string;
};

type RecalcPreview = {
    needs_change: boolean;
    current: Record<string, string | null>;
    proposed: Record<string, string | null>;
    delta: Record<string, string>;
};

type BalanceConsolidationCandidate = {
    user_id: number;
    name: string;
    email: string;
    total_withdrawable_usd: string;
    container_balance_before_usd: string;
    container_balance_after_usd: string;
    amount_to_move_usd: string;
    action_count: number;
};

type BulkConsolidationPreview = {
    user_count: number;
    action_count: number;
    total_amount_to_move_usd: string;
    users: Array<{
        user_id: number;
        name: string;
        email: string;
        amount_to_move_usd: string;
        container_balance_before_usd: string;
        container_balance_after_usd: string;
        actions: Array<{
            investment_id: number;
            txid: string;
            amount_usd: string;
            description: string;
        }>;
    }>;
};

const SECTION_URLS = {
    investments: '/admin/debug/secciones/inversiones',
    users: '/admin/debug/secciones/usuarios',
    manual: '/admin/debug/secciones/ajustes-manuales',
    consolidation: '/admin/debug/secciones/consolidacion-balance',
    accruals: '/admin/debug/secciones/acreditaciones',
} as const;

function formatDelta(value: string | null | undefined): string {
    if (!value) {
        return '—';
    }
    const n = Number.parseFloat(value);
    if (!Number.isFinite(n)) {
        return value;
    }
    if (n > 0) {
        return `+${n.toFixed(2)}`;
    }
    return n.toFixed(2);
}

function formatShortDatetime(iso: string | null): string {
    if (!iso) {
        return '—';
    }
    try {
        return new Intl.DateTimeFormat('es', {
            dateStyle: 'medium',
            timeStyle: 'short',
        }).format(new Date(iso));
    } catch {
        return iso;
    }
}

function AuditSectionLoading({ label = 'Cargando datos…' }: { label?: string }) {
    return (
        <div
            className="flex min-h-[120px] flex-col items-center justify-center gap-3 py-10 text-sm text-muted-foreground"
            role="status"
        >
            <Loader2 aria-hidden className="size-8 animate-spin text-primary" />
            <span>{label}</span>
        </div>
    );
}

export default function AdminDebugAudit() {
    const investmentSection = usePaginatedAuditSection<InvestmentBalanceIssue>(
        SECTION_URLS.investments,
    );
    const userSection = usePaginatedAuditSection<UserBalanceIssue>(SECTION_URLS.users);
    const manualSection = usePaginatedAuditSection<ManualBalanceCredit>(SECTION_URLS.manual);
    const consolidationSection = usePaginatedAuditSection<BalanceConsolidationCandidate>(
        SECTION_URLS.consolidation,
    );
    const accrualSection = usePaginatedAuditSection<AccrualInconsistency>(SECTION_URLS.accruals);

    const [revertTarget, setRevertTarget] = useState<ManualBalanceCredit | null>(null);
    const revertForm = useForm({});

    const [selectedUserIds, setSelectedUserIds] = useState<number[]>([]);
    const [consolidatePreview, setConsolidatePreview] = useState<BulkConsolidationPreview | null>(
        null,
    );
    const [consolidatePreviewLoading, setConsolidatePreviewLoading] = useState(false);
    const [consolidateModalOpen, setConsolidateModalOpen] = useState(false);
    const consolidateForm = useForm<{ user_ids: number[] }>({ user_ids: [] });

    const [recalcTarget, setRecalcTarget] = useState<AccrualInconsistency | null>(null);
    const [recalcPreview, setRecalcPreview] = useState<RecalcPreview | null>(null);
    const [recalcLoading, setRecalcLoading] = useState(false);
    const recalcForm = useForm({});

    const rescanAll = useCallback(() => {
        investmentSection.reload();
        userSection.reload();
        manualSection.reload();
        consolidationSection.reload();
        accrualSection.reload();
        setSelectedUserIds([]);
    }, [accrualSection, consolidationSection, investmentSection, manualSection, userSection]);

    const closeConsolidateModal = useCallback(() => {
        setConsolidateModalOpen(false);
        setConsolidatePreview(null);
        setConsolidatePreviewLoading(false);
    }, []);

    const openConsolidateModal = useCallback(async (userIds: number[]) => {
        const uniqueIds = [...new Set(userIds.filter((id) => id > 0))];
        if (uniqueIds.length === 0) {
            return;
        }

        setConsolidateModalOpen(true);
        setConsolidatePreview(null);
        setConsolidatePreviewLoading(true);
        consolidateForm.setData('user_ids', uniqueIds);

        try {
            const params = new URLSearchParams();
            uniqueIds.forEach((id) => params.append('user_ids[]', String(id)));

            const response = await fetch(
                `/admin/debug/consolidacion-balance/preview?${params.toString()}`,
                { headers: { Accept: 'application/json' }, credentials: 'same-origin' },
            );

            if (!response.ok) {
                throw new Error('preview failed');
            }

            setConsolidatePreview((await response.json()) as BulkConsolidationPreview);
        } catch {
            setConsolidatePreview(null);
        } finally {
            setConsolidatePreviewLoading(false);
        }
    }, [consolidateForm]);

    function executeBulkConsolidation() {
        if (consolidateForm.data.user_ids.length === 0) {
            return;
        }

        consolidateForm.post('/admin/debug/consolidacion-balance', {
            preserveScroll: true,
            onSuccess: () => {
                closeConsolidateModal();
                setSelectedUserIds([]);
                consolidationSection.reload();
                investmentSection.reload();
                userSection.reload();
            },
        });
    }

    const pageUserIds = useMemo(
        () => consolidationSection.data.map((row) => row.user_id),
        [consolidationSection.data],
    );

    const allPageSelected =
        pageUserIds.length > 0 && pageUserIds.every((id) => selectedUserIds.includes(id));

    const somePageSelected =
        pageUserIds.some((id) => selectedUserIds.includes(id)) && !allPageSelected;

    function toggleUserSelection(userId: number, checked: boolean) {
        setSelectedUserIds((current) =>
            checked ? [...new Set([...current, userId])] : current.filter((id) => id !== userId),
        );
    }

    function toggleAllPageSelection(checked: boolean) {
        if (checked) {
            setSelectedUserIds((current) => [...new Set([...current, ...pageUserIds])]);
        } else {
            setSelectedUserIds((current) => current.filter((id) => !pageUserIds.includes(id)));
        }
    }

    const closeRecalcModal = useCallback(() => {
        setRecalcTarget(null);
        setRecalcPreview(null);
        setRecalcLoading(false);
    }, []);

    const openRecalcModal = useCallback(async (row: AccrualInconsistency) => {
        setRecalcTarget(row);
        setRecalcPreview(null);
        setRecalcLoading(true);

        try {
            const response = await fetch(
                `/admin/acreditacion-mensual/movimientos/${row.transaction_id}/recalcular`,
                { headers: { Accept: 'application/json' }, credentials: 'same-origin' },
            );
            if (!response.ok) {
                throw new Error('preview failed');
            }
            setRecalcPreview((await response.json()) as RecalcPreview);
        } catch {
            setRecalcPreview(null);
        } finally {
            setRecalcLoading(false);
        }
    }, []);

    function applyRecalculation() {
        if (!recalcTarget) {
            return;
        }

        recalcForm.post(
            `/admin/acreditacion-mensual/movimientos/${recalcTarget.transaction_id}/recalcular`,
            {
                preserveScroll: true,
                onSuccess: () => {
                    closeRecalcModal();
                    accrualSection.reload();
                    investmentSection.reload();
                },
            },
        );
    }

    function executeRevertManualBalance() {
        if (!revertTarget?.user_id) {
            return;
        }

        revertForm.post(
            `/admin/debug/usuarios/${revertTarget.user_id}/balance-manual/${revertTarget.id}/revertir`,
            {
                preserveScroll: true,
                onSuccess: () => {
                    setRevertTarget(null);
                    manualSection.reload();
                    investmentSection.reload();
                },
            },
        );
    }

    const consolidationMeta = consolidationSection.meta as {
        total_amount_to_move_usd?: string;
    };

    const accrualMeta = accrualSection.meta as {
        scanned?: number;
        truncated?: boolean;
        total_period_accruals?: number;
    };

    const manualRevertableTotal =
        typeof manualSection.meta.revertable_total === 'number'
            ? manualSection.meta.revertable_total
            : null;

    return (
        <>
            <Head title="Auditoría" />

            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, revertir acreditación"
                confirmVariant="destructive"
                description="Elimina la acreditación manual del contenedor ADMIN-ADJ. Solo funciona si el usuario no ha consumido ese saldo."
                open={revertTarget !== null}
                processing={revertForm.processing}
                title={
                    revertTarget
                        ? `¿Revertir US$ ${revertTarget.amount_usd}?`
                        : 'Revertir acreditación'
                }
                onConfirm={executeRevertManualBalance}
                onOpenChange={(open) => !open && setRevertTarget(null)}
            >
                {revertTarget ? (
                    <div className="space-y-2 text-sm text-muted-foreground">
                        <p>
                            <span className="font-medium text-foreground">Usuario:</span>{' '}
                            {revertTarget.investor_name}
                        </p>
                        {revertTarget.admin_note ? (
                            <p>
                                <span className="font-medium text-foreground">Nota:</span>{' '}
                                {revertTarget.admin_note}
                            </p>
                        ) : null}
                    </div>
                ) : null}
            </ConfirmActionModal>

            <Dialog open={recalcTarget !== null} onOpenChange={(open) => !open && closeRecalcModal()}>
                <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-xl">
                    <DialogHeader>
                        <DialogTitle>Recalcular acreditación</DialogTitle>
                        <DialogDescription className="text-left">
                            Vista previa del ajuste según % pactado y mes de ejecución.
                        </DialogDescription>
                    </DialogHeader>

                    {recalcLoading ? (
                        <p className="flex items-center gap-2 py-4 text-sm text-muted-foreground">
                            <Loader2 className="size-4 animate-spin" />
                            Calculando…
                        </p>
                    ) : null}

                    {!recalcLoading && recalcPreview?.needs_change ? (
                        <div className="space-y-3 text-sm">
                            <div className="grid gap-2 rounded-md border p-3">
                                <p>
                                    <span className="text-muted-foreground">Período:</span>{' '}
                                    {recalcPreview.current.period_label ?? '—'} →{' '}
                                    <span className="font-medium">
                                        {recalcPreview.proposed.period_label ?? '—'}
                                    </span>
                                </p>
                                <p>
                                    <span className="text-muted-foreground">Ganancia:</span>{' '}
                                    {recalcPreview.current.gain_usd} →{' '}
                                    <span className="font-medium text-primary">
                                        {recalcPreview.proposed.gain_usd} US$
                                    </span>{' '}
                                    ({formatDelta(recalcPreview.delta.gain_usd)})
                                </p>
                                <p>
                                    <span className="text-muted-foreground">Balance usuario:</span>{' '}
                                    {formatDelta(recalcPreview.delta.user_ledger_balance_usd)} US$
                                </p>
                            </div>
                        </div>
                    ) : null}

                    <DialogFooter className="gap-2 sm:gap-0">
                        <Button type="button" variant="ghost" onClick={closeRecalcModal}>
                            Cancelar
                        </Button>
                        <Button
                            disabled={recalcForm.processing || !recalcPreview?.needs_change}
                            type="button"
                            onClick={applyRecalculation}
                        >
                            Aplicar ajuste
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <Dialog open={consolidateModalOpen} onOpenChange={(open) => !open && closeConsolidateModal()}>
                <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
                    <DialogHeader>
                        <DialogTitle>Consolidar saldo retirable</DialogTitle>
                        <DialogDescription className="text-left">
                            Vista previa de los movimientos internos que se aplicarán al balance general
                            de cada usuario.
                        </DialogDescription>
                    </DialogHeader>

                    {consolidatePreviewLoading ? (
                        <p className="flex items-center gap-2 py-4 text-sm text-muted-foreground">
                            <Loader2 className="size-4 animate-spin" />
                            Calculando cambios…
                        </p>
                    ) : null}

                    {!consolidatePreviewLoading && consolidatePreview ? (
                        <div className="space-y-4 text-sm">
                            <div className="grid gap-2 rounded-md border bg-muted/30 p-3 sm:grid-cols-3">
                                <p>
                                    <span className="text-muted-foreground">Usuarios:</span>{' '}
                                    <span className="font-medium tabular-nums">
                                        {consolidatePreview.user_count}
                                    </span>
                                </p>
                                <p>
                                    <span className="text-muted-foreground">Acciones:</span>{' '}
                                    <span className="font-medium tabular-nums">
                                        {consolidatePreview.action_count}
                                    </span>
                                </p>
                                <p>
                                    <span className="text-muted-foreground">Total a mover:</span>{' '}
                                    <span className="font-semibold tabular-nums text-primary">
                                        US$ {consolidatePreview.total_amount_to_move_usd}
                                    </span>
                                </p>
                            </div>

                            {consolidatePreview.users.length === 0 ? (
                                <p className="text-muted-foreground">
                                    No hay saldo retirable disperso pendiente para los usuarios
                                    seleccionados.
                                </p>
                            ) : (
                                <div className="max-h-[50vh] space-y-4 overflow-y-auto pr-1">
                                    {consolidatePreview.users.map((userRow) => (
                                        <div
                                            key={userRow.user_id}
                                            className="space-y-2 rounded-md border p-3"
                                        >
                                            <div className="flex flex-wrap items-start justify-between gap-2">
                                                <div>
                                                    <p className="font-medium">{userRow.name}</p>
                                                    <p className="text-xs text-muted-foreground">
                                                        {userRow.email}
                                                    </p>
                                                </div>
                                                <p className="text-xs tabular-nums">
                                                    Balance general:{' '}
                                                    {userRow.container_balance_before_usd} →{' '}
                                                    <span className="font-semibold text-primary">
                                                        {userRow.container_balance_after_usd} US$
                                                    </span>
                                                </p>
                                            </div>
                                            <ul className="space-y-1.5 text-xs leading-relaxed text-muted-foreground">
                                                {userRow.actions.map((action) => (
                                                    <li
                                                        key={`${userRow.user_id}-${action.investment_id}-${action.txid}`}
                                                    >
                                                        {action.description}
                                                    </li>
                                                ))}
                                            </ul>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>
                    ) : null}

                    {!consolidatePreviewLoading && !consolidatePreview ? (
                        <p className="text-sm text-destructive">
                            No se pudo cargar la vista previa. Inténtalo de nuevo.
                        </p>
                    ) : null}

                    <DialogFooter className="gap-2 sm:gap-0">
                        <Button type="button" variant="ghost" onClick={closeConsolidateModal}>
                            Cancelar
                        </Button>
                        <Button
                            disabled={
                                consolidateForm.processing ||
                                consolidatePreviewLoading ||
                                !consolidatePreview ||
                                consolidatePreview.user_count === 0
                            }
                            type="button"
                            onClick={executeBulkConsolidation}
                        >
                            {consolidateForm.processing ? 'Consolidando…' : 'Confirmar consolidación'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <div className="mx-auto max-w-6xl space-y-6 p-4">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight sm:text-3xl">Auditoría</h1>
                    <p className="mt-2 text-sm text-muted-foreground">
                        Herramientas de auditoría y corrección. Cada sección se carga por separado.
                    </p>
                </div>

                <Alert className="border-amber-500/40 bg-amber-500/10">
                    <AlertTitle className="text-amber-950 dark:text-amber-100">
                        Ajustes administrativos
                    </AlertTitle>
                    <AlertDescription className="text-amber-950/80 dark:text-amber-100/80">
                        Revise inconsistencias antes de aplicar correcciones. Los recálculos de
                        acreditación modifican el libro contable de la inversión.
                    </AlertDescription>
                </Alert>

                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-6">
                    <SummaryCard
                        label="Inversiones desalineadas"
                        loading={investmentSection.loading}
                        value={investmentSection.paginator?.total ?? null}
                    />
                    <SummaryCard
                        label="Usuarios desalineados"
                        loading={userSection.loading}
                        value={userSection.paginator?.total ?? null}
                    />
                    <SummaryCard
                        label="Pendientes de consolidar"
                        loading={consolidationSection.loading}
                        value={consolidationSection.paginator?.total ?? null}
                    />
                    <SummaryCard
                        label="Ajustes manuales"
                        loading={manualSection.loading}
                        value={manualSection.paginator?.total ?? null}
                    />
                    <SummaryCard
                        label="Ajustes revertibles"
                        loading={manualSection.loading}
                        value={manualRevertableTotal}
                    />
                    <SummaryCard
                        label="Acreditaciones a corregir"
                        loading={accrualSection.loading}
                        value={accrualSection.paginator?.total ?? null}
                    />
                </div>

                <Card>
                    <CardHeader>
                        <CardTitle>1. Inconsistencias de balances</CardTitle>
                        <CardDescription>
                            Compara{' '}
                            <code className="text-xs">capital_balance</code> almacenado vs capital
                            reconstruido desde movimientos, y saldo retirable agregado por usuario.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-6">
                        <section>
                            <h3 className="mb-3 text-sm font-semibold">Por inversión</h3>
                            {investmentSection.loading ? (
                                <AuditSectionLoading label="Analizando inversiones…" />
                            ) : investmentSection.error ? (
                                <SectionError message={investmentSection.error} />
                            ) : investmentSection.data.length === 0 ? (
                                <p className="text-sm text-muted-foreground">
                                    No se detectaron desvíos de capital en las inversiones
                                    revisadas.
                                </p>
                            ) : (
                                <div className="overflow-x-auto rounded-md border">
                                    <table className="w-full min-w-[880px] text-left text-sm">
                                        <thead>
                                            <tr className="border-b bg-muted/40 text-muted-foreground">
                                                <th className="px-3 py-2 font-medium">Inversión</th>
                                                <th className="px-3 py-2 font-medium">Inversionista</th>
                                                <th className="px-3 py-2 font-medium tabular-nums">
                                                    Almacenado
                                                </th>
                                                <th className="px-3 py-2 font-medium tabular-nums">
                                                    Calculado
                                                </th>
                                                <th className="px-3 py-2 font-medium tabular-nums">
                                                    Δ
                                                </th>
                                                <th className="px-3 py-2 font-medium">Movimientos</th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y">
                                            {investmentSection.data.map((row) => (
                                                <tr key={row.investment_id}>
                                                    <td className="px-3 py-2">
                                                        <div className="font-mono text-xs">
                                                            {row.txid}
                                                        </div>
                                                        {row.is_admin_adjustment ? (
                                                            <Badge
                                                                className="mt-1 text-xs font-normal"
                                                                variant="outline"
                                                            >
                                                                ADMIN-ADJ
                                                            </Badge>
                                                        ) : null}
                                                    </td>
                                                    <td className="px-3 py-2">
                                                        <div>{row.investor_name}</div>
                                                        <div className="text-xs text-muted-foreground">
                                                            {row.investor_email}
                                                        </div>
                                                    </td>
                                                    <td className="px-3 py-2 tabular-nums">
                                                        {row.stored_capital_usd} US$
                                                    </td>
                                                    <td className="px-3 py-2 tabular-nums">
                                                        {row.computed_capital_usd} US$
                                                    </td>
                                                    <td
                                                        className={cn(
                                                            'px-3 py-2 tabular-nums font-medium',
                                                            Number.parseFloat(row.capital_delta_usd) !==
                                                                0 &&
                                                                'text-amber-600 dark:text-amber-400',
                                                        )}
                                                    >
                                                        {formatDelta(row.capital_delta_usd)} US$
                                                    </td>
                                                    <td className="px-3 py-2 text-xs text-muted-foreground">
                                                        {row.transaction_mismatches.length === 0
                                                            ? 'Capital total'
                                                            : row.transaction_mismatches
                                                                  .map(
                                                                      (m) =>
                                                                          `#${m.transaction_id}: ${m.stored_usd ?? '—'} → ${m.expected_usd}`,
                                                                  )
                                                                  .join(' · ')}
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                    {investmentSection.paginator ? (
                                        <JsonPaginatorFooter
                                            disabled={investmentSection.loading}
                                            paginator={investmentSection.paginator}
                                            onPageChange={investmentSection.setPage}
                                        />
                                    ) : null}
                                </div>
                            )}
                        </section>

                        <section>
                            <h3 className="mb-3 text-sm font-semibold">
                                Saldo retirable por usuario
                            </h3>
                            {userSection.loading ? (
                                <AuditSectionLoading label="Analizando saldos retirables…" />
                            ) : userSection.error ? (
                                <SectionError message={userSection.error} />
                            ) : userSection.data.length === 0 ? (
                                <p className="text-sm text-muted-foreground">
                                    Los totales retirables coinciden con la suma por inversión.
                                </p>
                            ) : (
                                <div className="overflow-x-auto rounded-md border">
                                    <table className="w-full min-w-[640px] text-left text-sm">
                                        <thead>
                                            <tr className="border-b bg-muted/40 text-muted-foreground">
                                                <th className="px-3 py-2 font-medium">Usuario</th>
                                                <th className="px-3 py-2 font-medium tabular-nums">
                                                    Reportado
                                                </th>
                                                <th className="px-3 py-2 font-medium tabular-nums">
                                                    Suma inversiones
                                                </th>
                                                <th className="px-3 py-2 font-medium tabular-nums">
                                                    Δ
                                                </th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y">
                                            {userSection.data.map((row) => (
                                                <tr key={row.user_id}>
                                                    <td className="px-3 py-2">
                                                        <div>{row.name}</div>
                                                        <div className="text-xs text-muted-foreground">
                                                            {row.email}
                                                        </div>
                                                    </td>
                                                    <td className="px-3 py-2 tabular-nums">
                                                        {row.reported_withdrawable_usd} US$
                                                    </td>
                                                    <td className="px-3 py-2 tabular-nums">
                                                        {row.sum_investment_withdrawable_usd} US$
                                                    </td>
                                                    <td className="px-3 py-2 tabular-nums font-medium text-amber-600 dark:text-amber-400">
                                                        {formatDelta(row.delta_usd)} US$
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                    {userSection.paginator ? (
                                        <JsonPaginatorFooter
                                            disabled={userSection.loading}
                                            paginator={userSection.paginator}
                                            onPageChange={userSection.setPage}
                                        />
                                    ) : null}
                                </div>
                            )}
                        </section>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader>
                        <div className="flex flex-wrap items-start justify-between gap-3">
                            <div>
                                <CardTitle className="flex items-center gap-2">
                                    <Layers className="size-5 text-primary" />
                                    2. Consolidación de saldo retirable
                                </CardTitle>
                                <CardDescription>
                                    Usuarios con saldo retirable aún disperso en inversiones
                                    individuales. Consolida al balance general (contenedor ADMIN-ADJ).
                                    {consolidationSection.loading ? (
                                        ' Cargando…'
                                    ) : consolidationMeta.total_amount_to_move_usd ? (
                                        <>
                                            {' '}
                                            Total pendiente: US${' '}
                                            {consolidationMeta.total_amount_to_move_usd}.
                                        </>
                                    ) : null}
                                </CardDescription>
                            </div>
                            <div className="flex flex-wrap gap-2">
                                <Button
                                    disabled={
                                        selectedUserIds.length === 0 ||
                                        consolidationSection.loading ||
                                        consolidatePreviewLoading
                                    }
                                    size="sm"
                                    type="button"
                                    variant="secondary"
                                    onClick={() => openConsolidateModal(selectedUserIds)}
                                >
                                    Consolidar seleccionados ({selectedUserIds.length})
                                </Button>
                                <Button
                                    disabled={
                                        consolidationSection.data.length === 0 ||
                                        consolidationSection.loading ||
                                        consolidatePreviewLoading
                                    }
                                    size="sm"
                                    type="button"
                                    onClick={() => openConsolidateModal(pageUserIds)}
                                >
                                    Consolidar página actual
                                </Button>
                            </div>
                        </div>
                    </CardHeader>
                    <CardContent className="overflow-x-auto p-0">
                        {consolidationSection.loading ? (
                            <AuditSectionLoading label="Buscando saldo retirable disperso…" />
                        ) : consolidationSection.error ? (
                            <SectionError message={consolidationSection.error} />
                        ) : consolidationSection.data.length === 0 ? (
                            <p className="p-6 text-sm text-muted-foreground">
                                No hay usuarios con saldo retirable pendiente de consolidar.
                            </p>
                        ) : (
                            <>
                                <table className="w-full min-w-[920px] text-left text-sm">
                                    <thead>
                                        <tr className="border-b bg-muted/40 text-muted-foreground">
                                            <th className="w-10 px-3 py-3">
                                                <Checkbox
                                                    aria-label="Seleccionar todos en esta página"
                                                    checked={
                                                        allPageSelected
                                                            ? true
                                                            : somePageSelected
                                                              ? 'indeterminate'
                                                              : false
                                                    }
                                                    onCheckedChange={(value) =>
                                                        toggleAllPageSelection(value === true)
                                                    }
                                                />
                                            </th>
                                            <th className="px-3 py-3 font-medium">Usuario</th>
                                            <th className="px-3 py-3 font-medium tabular-nums">
                                                Saldo retirable
                                            </th>
                                            <th className="px-3 py-3 font-medium tabular-nums">
                                                Balance general
                                            </th>
                                            <th className="px-3 py-3 font-medium tabular-nums">
                                                Tras consolidar
                                            </th>
                                            <th className="px-3 py-3 font-medium tabular-nums">
                                                A mover
                                            </th>
                                            <th className="px-3 py-3 font-medium tabular-nums">
                                                Acciones
                                            </th>
                                            <th className="px-3 py-3 font-medium">Operación</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y">
                                        {consolidationSection.data.map((row) => (
                                            <tr key={row.user_id}>
                                                <td className="px-3 py-3">
                                                    <Checkbox
                                                        aria-label={`Seleccionar ${row.name}`}
                                                        checked={selectedUserIds.includes(row.user_id)}
                                                        onCheckedChange={(value) =>
                                                            toggleUserSelection(
                                                                row.user_id,
                                                                value === true,
                                                            )
                                                        }
                                                    />
                                                </td>
                                                <td className="px-3 py-3">
                                                    <div className="font-medium">{row.name}</div>
                                                    <div className="text-xs text-muted-foreground">
                                                        {row.email}
                                                    </div>
                                                </td>
                                                <td className="px-3 py-3 tabular-nums">
                                                    {row.total_withdrawable_usd} US$
                                                </td>
                                                <td className="px-3 py-3 tabular-nums">
                                                    {row.container_balance_before_usd} US$
                                                </td>
                                                <td className="px-3 py-3 tabular-nums text-primary">
                                                    {row.container_balance_after_usd} US$
                                                </td>
                                                <td className="px-3 py-3 tabular-nums font-medium">
                                                    {row.amount_to_move_usd} US$
                                                </td>
                                                <td className="px-3 py-3 tabular-nums">
                                                    {row.action_count}
                                                </td>
                                                <td className="px-3 py-3">
                                                    <div className="flex flex-wrap gap-2">
                                                        <Button
                                                            size="sm"
                                                            type="button"
                                                            variant="outline"
                                                            onClick={() =>
                                                                openConsolidateModal([row.user_id])
                                                            }
                                                        >
                                                            Ver detalle
                                                        </Button>
                                                        <Button asChild size="sm" variant="ghost">
                                                            <Link
                                                                href={`/admin/usuarios/${row.user_id}/editar`}
                                                            >
                                                                Usuario
                                                            </Link>
                                                        </Button>
                                                    </div>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                                {consolidationSection.paginator ? (
                                    <JsonPaginatorFooter
                                        disabled={consolidationSection.loading}
                                        paginator={consolidationSection.paginator}
                                        onPageChange={consolidationSection.setPage}
                                    />
                                ) : null}
                            </>
                        )}
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader>
                        <CardTitle>3. Balances acreditados manualmente</CardTitle>
                        <CardDescription>
                            Créditos ADMIN-ADJ aplicados desde Usuarios. Puede revertirlos aquí si el
                            saldo del contenedor aún lo permite.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="overflow-x-auto p-0">
                        {manualSection.loading ? (
                            <AuditSectionLoading label="Cargando ajustes manuales…" />
                        ) : manualSection.error ? (
                            <SectionError message={manualSection.error} />
                        ) : manualSection.data.length === 0 ? (
                            <p className="p-6 text-sm text-muted-foreground">
                                No hay acreditaciones manuales registradas.
                            </p>
                        ) : (
                            <>
                                <table className="w-full min-w-[820px] text-left text-sm">
                                    <thead>
                                        <tr className="border-b bg-muted/40 text-muted-foreground">
                                            <th className="px-4 py-3 font-medium">Usuario</th>
                                            <th className="px-4 py-3 font-medium tabular-nums">Monto</th>
                                            <th className="px-4 py-3 font-medium tabular-nums">
                                                Contenedor
                                            </th>
                                            <th className="px-4 py-3 font-medium">Nota</th>
                                            <th className="px-4 py-3 font-medium">Fecha</th>
                                            <th className="px-4 py-3 font-medium">Acciones</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y">
                                        {manualSection.data.map((credit) => (
                                            <tr key={credit.id}>
                                                <td className="px-4 py-3">
                                                    <div className="font-medium">
                                                        {credit.investor_name}
                                                    </div>
                                                    <div className="text-xs text-muted-foreground">
                                                        {credit.investor_email}
                                                    </div>
                                                </td>
                                                <td className="px-4 py-3 tabular-nums font-medium text-primary">
                                                    {credit.amount_usd} US$
                                                </td>
                                                <td className="px-4 py-3 tabular-nums">
                                                    {credit.container_balance_usd} US$
                                                </td>
                                                <td className="max-w-[200px] truncate px-4 py-3 text-muted-foreground">
                                                    {credit.admin_note ?? '—'}
                                                </td>
                                                <td className="whitespace-nowrap px-4 py-3 text-xs text-muted-foreground">
                                                    {formatShortDatetime(credit.created_at)}
                                                    {credit.created_by ? (
                                                        <div>por {credit.created_by}</div>
                                                    ) : null}
                                                </td>
                                                <td className="px-4 py-3">
                                                    <div className="flex flex-wrap gap-2">
                                                        {credit.user_id ? (
                                                            <Button asChild size="sm" variant="outline">
                                                                <Link
                                                                    href={`/admin/usuarios/${credit.user_id}/editar`}
                                                                >
                                                                    Ver usuario
                                                                </Link>
                                                            </Button>
                                                        ) : null}
                                                        {credit.can_revert ? (
                                                            <Button
                                                                size="sm"
                                                                variant="destructive"
                                                                onClick={() => setRevertTarget(credit)}
                                                            >
                                                                Revertir
                                                            </Button>
                                                        ) : (
                                                            <span className="text-xs text-muted-foreground">
                                                                No revertible
                                                            </span>
                                                        )}
                                                    </div>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                                {manualSection.paginator ? (
                                    <JsonPaginatorFooter
                                        disabled={manualSection.loading}
                                        paginator={manualSection.paginator}
                                        onPageChange={manualSection.setPage}
                                    />
                                ) : null}
                            </>
                        )}
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader>
                        <CardTitle>4. Acreditaciones con inconsistencias</CardTitle>
                        <CardDescription>
                            Períodos o montos que no coinciden con el % pactado y el mes de
                            ejecución.
                            {accrualSection.loading ? (
                                ' Escaneando…'
                            ) : (
                                <>
                                    {' '}
                                    Escaneadas {accrualMeta.scanned ?? 0} de{' '}
                                    {accrualMeta.total_period_accruals ?? 0}.
                                    {accrualMeta.truncated ? ' Listado parcial (límite de escaneo).' : null}
                                </>
                            )}
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="overflow-x-auto p-0">
                        {accrualSection.loading ? (
                            <AuditSectionLoading label="Escaneando acreditaciones…" />
                        ) : accrualSection.error ? (
                            <SectionError message={accrualSection.error} />
                        ) : accrualSection.data.length === 0 ? (
                            <p className="p-6 text-sm text-muted-foreground">
                                No se encontraron acreditaciones por período desalineadas en el
                                rango escaneado.
                            </p>
                        ) : (
                            <>
                                <table className="w-full min-w-[980px] text-left text-sm">
                                    <thead>
                                        <tr className="border-b bg-muted/40 text-muted-foreground">
                                            <th className="px-4 py-3 font-medium">Inversión</th>
                                            <th className="px-4 py-3 font-medium">Ejecución</th>
                                            <th className="px-4 py-3 font-medium">Período actual</th>
                                            <th className="px-4 py-3 font-medium">Período correcto</th>
                                            <th className="px-4 py-3 font-medium tabular-nums">
                                                Ganancia
                                            </th>
                                            <th className="px-4 py-3 font-medium tabular-nums">Δ</th>
                                            <th className="px-4 py-3 font-medium">Acciones</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y">
                                        {accrualSection.data.map((row) => (
                                            <tr key={row.transaction_id}>
                                                <td className="px-4 py-3">
                                                    <div className="font-medium">
                                                        {row.investor_name}
                                                    </div>
                                                    <div className="font-mono text-xs text-muted-foreground">
                                                        {row.txid.substring(0, 8)}...
                                                    </div>
                                                    {row.is_imported ? (
                                                        <Badge
                                                            className="mt-1 text-xs font-normal"
                                                            variant="outline"
                                                        >
                                                            Importada
                                                        </Badge>
                                                    ) : null}
                                                </td>
                                                <td className="px-4 py-3 text-xs">{row.accrual_on}</td>
                                                <td className="px-4 py-3 text-xs text-muted-foreground">
                                                    <div>{row.current_period_label ?? '—'}</div>
                                                    <div>{row.current_period ?? '—'}</div>
                                                    <div className="tabular-nums">
                                                        {row.current_gain_usd} US$
                                                    </div>
                                                </td>
                                                <td className="px-4 py-3 text-xs">
                                                    <div className="font-medium">
                                                        {row.proposed_period_label ?? '—'}
                                                    </div>
                                                    <div>{row.proposed_period ?? '—'}</div>
                                                    <div className="tabular-nums text-primary">
                                                        {row.proposed_gain_usd} US$
                                                    </div>
                                                </td>
                                                <td className="px-4 py-3 tabular-nums">
                                                    {row.current_gain_usd} → {row.proposed_gain_usd}
                                                </td>
                                                <td className="px-4 py-3 tabular-nums font-medium">
                                                    {formatDelta(row.gain_delta_usd)} US$
                                                </td>
                                                <td className="px-4 py-3">
                                                    <div className="flex flex-wrap gap-2">
                                                        <Button asChild size="sm" variant="outline">
                                                            <Link href={row.accrual_run_url}>
                                                                <ExternalLink className="size-3.5" />
                                                                Ejecución
                                                            </Link>
                                                        </Button>
                                                        <Button
                                                            size="sm"
                                                            variant="secondary"
                                                            onClick={() => openRecalcModal(row)}
                                                        >
                                                            <RefreshCw className="size-3.5" />
                                                            Recalcular
                                                        </Button>
                                                    </div>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                                {accrualSection.paginator ? (
                                    <JsonPaginatorFooter
                                        disabled={accrualSection.loading}
                                        paginator={accrualSection.paginator}
                                        onPageChange={accrualSection.setPage}
                                    />
                                ) : null}
                            </>
                        )}
                    </CardContent>
                </Card>

                <div className="flex justify-end">
                    <Button
                        disabled={
                            investmentSection.loading ||
                            userSection.loading ||
                            manualSection.loading ||
                            consolidationSection.loading ||
                            accrualSection.loading
                        }
                        type="button"
                        variant="outline"
                        onClick={rescanAll}
                    >
                        {investmentSection.loading ||
                        userSection.loading ||
                        manualSection.loading ||
                        consolidationSection.loading ||
                        accrualSection.loading ? (
                            <Loader2 className="size-4 animate-spin" />
                        ) : (
                            <RefreshCw className="size-4" />
                        )}
                        Volver a escanear
                    </Button>
                </div>
            </div>
        </>
    );
}

function SectionError({ message }: { message: string }) {
    return <p className="py-4 text-sm text-destructive">{message}</p>;
}

function SummaryCard({
    label,
    value,
    loading,
}: {
    label: string;
    value: number | null;
    loading?: boolean;
}) {
    return (
        <Card>
            <CardHeader className="pb-2">
                <CardDescription>{label}</CardDescription>
                <CardTitle className="text-2xl tabular-nums">
                    {loading ? (
                        <Loader2 aria-hidden className="size-7 animate-spin text-muted-foreground" />
                    ) : (
                        (value ?? 0)
                    )}
                </CardTitle>
            </CardHeader>
        </Card>
    );
}

AdminDebugAudit.layout = {
    breadcrumbs: [
        { title: 'Administración', href: '/admin' },
        { title: 'Auditoría', href: '/admin/debug' },
    ],
};
