import { Head, Link, router, useForm } from '@inertiajs/react';
import { FileWarning, Loader2, Pencil, Trash2 } from 'lucide-react';
import type { FormEvent } from 'react';
import { useState } from 'react';
import { ConfirmActionModal } from '@/components/confirm-action-modal';
import InputError from '@/components/input-error';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
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 { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { countryOptions } from '@/lib/countries';

export type AccrualPreviewLine = {
    month_label: string;
    accrual_run_date: string | null;
    period_start: string;
    period_end: string;
    gain_usd: number;
    balance_after: number;
};

export type AccrualPreview = {
    mode: string;
    accrual_day_of_month: number | null;
    cutoff_date: string;
    lines: AccrualPreviewLine[];
    total_gain_usd: number;
    final_balance_usd: number;
    runs_count: number;
};

export type ForexStagingAccrualGroup = {
    total_gain_usd: number;
    cutoff_date: string;
    mode: string;
    accrual_day_of_month: number | null;
};

export type ForexStagingPlanRow = {
    id: number;
    csv_record_index: number;
    email_hint: string;
    first_name: string | null;
    last_name: string | null;
    contact_number: string | null;
    country: string | null;
    amount: string;
    duration_months: number;
    confirmed_at: string | null;
    maturity_at: string | null;
    monthly_return_snapshot: string;
    wallet_address: string | null;
    csv_saldo_ganancias?: string | null;
    csv_saldo_total?: string | null;
    csv_saldo_bloqueado?: string | null;
    csv_saldo_pagado?: string | null;
    accrual_preview: AccrualPreview;
};

export type ForexStagingPortfolio = {
    withdrawable_usd: number;
    principal_locked_usd: number;
    capital_in_contracts_usd: number;
    active_investments: number;
    pending_investments: number;
};

export type ForexStagingGroup = {
    email: string;
    email_key: string;
    is_new_user: boolean;
    proposed: {
        first_name: string | null;
        last_name: string | null;
        contact_number: string | null;
        country: string | null;
        wallet_address: string | null;
    };
    existing_user: {
        id: number;
        name: string;
        email: string;
        kyc_status: string;
    } | null;
    portfolio: ForexStagingPortfolio | null;
    plans: ForexStagingPlanRow[];
    plans_count: number;
    new_principal_total_usd: number;
    accrual_group: ForexStagingAccrualGroup;
};

type Props = {
    groups: ForexStagingGroup[];
    groups_count: number;
    pending_count: number;
};

function formatUsd(amount: string | number): string {
    return new Intl.NumberFormat('es-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
    }).format(Number(amount));
}

function formatDateShort(iso: string | null): string {
    if (!iso) {
        return '—';
    }
    return new Date(iso).toLocaleString('es', {
        dateStyle: 'short',
    });
}

function countrySelectValue(country: string | null | undefined): string {
    if (country && countryOptions.some((o) => o.value === country)) {
        return country;
    }

    return 'OTHER';
}

function isoDateToInput(iso: string | null | undefined): string {
    if (!iso) {
        return '';
    }

    return iso.slice(0, 10);
}

function accrualModeSummary(group: ForexStagingGroup): string {
    const m = group.accrual_group.mode;
    if (m === 'monthly') {
        const d = group.accrual_group.accrual_day_of_month;
        return d != null
            ? `Modo mensual · días de ejecución: ${d} de cada mes (según ajuste de meses cortos).`
            : 'Modo mensual.';
    }
    return 'Modo diario · la tabla muestra totales agrupados por mes natural.';
}

export default function ForexImportStaging({
    groups,
    groups_count,
    pending_count,
}: Props) {
    const [approvingEmail, setApprovingEmail] = useState<string | null>(null);
    const [discardingEmail, setDiscardingEmail] = useState<string | null>(null);
    const [approveTarget, setApproveTarget] = useState<ForexStagingGroup | null>(null);
    const [editingPlan, setEditingPlan] = useState<ForexStagingPlanRow | null>(null);
    const [deletePlanTarget, setDeletePlanTarget] = useState<ForexStagingPlanRow | null>(null);
    const [deletingPlanId, setDeletingPlanId] = useState<number | null>(null);
    const [discardGroupTarget, setDiscardGroupTarget] = useState<ForexStagingGroup | null>(null);

    const editForm = useForm({
        email_hint: '',
        first_name: '',
        last_name: '',
        contact_number: '',
        country: 'OTHER' as string,
        wallet_address: '',
        amount: '',
        duration_months: 12,
        confirmed_at: '',
        maturity_at: '',
        monthly_return_snapshot: '',
    });

    function requestApprove(group: ForexStagingGroup) {
        setApproveTarget(group);
    }

    function executeApprove() {
        if (!approveTarget) {
            return;
        }
        const { email } = approveTarget;
        setApprovingEmail(email);
        router.post(
            '/admin/importacion-forex/aprobar',
            { email },
            {
                preserveScroll: true,
                onFinish: () => {
                    setApprovingEmail(null);
                    setApproveTarget(null);
                },
            },
        );
    }

    const approveProcessing =
        approveTarget != null && approvingEmail === approveTarget.email;

    function openEditPlan(plan: ForexStagingPlanRow) {
        setEditingPlan(plan);
        editForm.setData({
            email_hint: plan.email_hint,
            first_name: plan.first_name ?? '',
            last_name: plan.last_name ?? '',
            contact_number: plan.contact_number ?? '',
            country: countrySelectValue(plan.country),
            wallet_address: plan.wallet_address ?? '',
            amount: plan.amount,
            duration_months: plan.duration_months,
            confirmed_at: isoDateToInput(plan.confirmed_at),
            maturity_at: isoDateToInput(plan.maturity_at),
            monthly_return_snapshot: plan.monthly_return_snapshot,
        });
        editForm.clearErrors();
    }

    function closeEditPlan() {
        setEditingPlan(null);
        editForm.reset();
        editForm.clearErrors();
    }

    function submitEditPlan(e: FormEvent) {
        e.preventDefault();
        if (!editingPlan) {
            return;
        }

        editForm.transform((data) => ({
            ...data,
            first_name: data.first_name.trim() === '' ? null : data.first_name,
            last_name: data.last_name.trim() === '' ? null : data.last_name,
            contact_number: data.contact_number.trim() === '' ? null : data.contact_number,
            wallet_address: data.wallet_address.trim() === '' ? null : data.wallet_address,
            confirmed_at: data.confirmed_at.trim() === '' ? null : data.confirmed_at,
            maturity_at: data.maturity_at.trim() === '' ? null : data.maturity_at,
        }));

        editForm.patch(`/admin/importacion-forex/item/${editingPlan.id}`, {
            preserveScroll: true,
            onSuccess: () => closeEditPlan(),
        });
    }

    function executeDeletePlan() {
        if (!deletePlanTarget) {
            return;
        }
        const id = deletePlanTarget.id;
        setDeletingPlanId(id);
        router.delete(`/admin/importacion-forex/item/${id}`, {
            preserveScroll: true,
            onFinish: () => {
                setDeletingPlanId(null);
                setDeletePlanTarget(null);
            },
        });
    }

    function executeDiscardGroup() {
        if (!discardGroupTarget) {
            return;
        }
        const email = discardGroupTarget.email;
        setDiscardingEmail(email);
        router.post(
            '/admin/importacion-forex/descartar-correo',
            { email },
            {
                preserveScroll: true,
                onFinish: () => {
                    setDiscardingEmail(null);
                    setDiscardGroupTarget(null);
                },
            },
        );
    }

    const discardGroupProcessing =
        discardGroupTarget != null && discardingEmail === discardGroupTarget.email;

    return (
        <>
            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, aprobar e inscribir intereses"
                description={
                    <>
                        Se crearán las inversiones activas con depósito inicial y, con la misma lógica que usa la
                        plataforma (diaria o mensual), los intereses desde la fecha de inicio hasta la fecha de corte
                        indicada.{' '}
                        <strong className="text-foreground">
                            Es irreversible en el sentido operativo: los movimientos quedan en el libro; corregirlos
                            implica operaciones manuales adicionales.
                        </strong>
                    </>
                }
                open={approveTarget !== null}
                processing={approveProcessing}
                title="Confirmar aprobación e intereses atrasados"
                onConfirm={executeApprove}
                onOpenChange={(open) => {
                    if (!open && !approveProcessing) {
                        setApproveTarget(null);
                    }
                }}
            >
                {approveTarget ? (
                    <div className="space-y-3">
                        <p className="text-muted-foreground text-xs">
                            <strong className="text-foreground">Correo:</strong> {approveTarget.email}
                        </p>
                        <p className="text-xs">{accrualModeSummary(approveTarget)}</p>
                        <p className="text-xs">
                            <strong className="text-foreground">Fecha de corte</strong> (ahoy):{' '}
                            {approveTarget.accrual_group.cutoff_date}
                        </p>
                        <p className="text-amber-700 text-xs dark:text-amber-500">
                            Ganancia de intereses simulada ({approveTarget.plans_count} plan
                            {approveTarget.plans_count === 1 ? '' : 'es'}):{' '}
                            <strong className="tabular-nums">
                                $ {formatUsd(approveTarget.accrual_group.total_gain_usd)}
                            </strong>
                        </p>
                        <div className="overflow-x-auto rounded border">
                            <table className="w-full min-w-[280px] text-left text-xs">
                                <thead>
                                    <tr className="text-muted-foreground border-b">
                                        <th className="px-2 py-1.5 font-medium"># CSV</th>
                                        <th className="px-2 py-1.5 text-right font-medium">Intereses</th>
                                        <th className="px-2 py-1.5 text-right font-medium">
                                            Saldo simulado
                                        </th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y">
                                    {approveTarget.plans.map((plan) => (
                                        <tr key={plan.id}>
                                            <td className="px-2 py-1.5 tabular-nums">
                                                {plan.csv_record_index}
                                            </td>
                                            <td className="px-2 py-1.5 text-right tabular-nums">
                                                $ {formatUsd(plan.accrual_preview.total_gain_usd)}
                                            </td>
                                            <td className="px-2 py-1.5 text-right tabular-nums">
                                                $ {formatUsd(plan.accrual_preview.final_balance_usd)}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                ) : null}
            </ConfirmActionModal>

            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, eliminar permanentemente"
                confirmVariant="destructive"
                description="Se borrará este plan de la cola de importación. La acción es permanente e irreversible: no podrás restaurarlo desde aquí; si lo necesitas, tendrás que volver a cargar el CSV."
                open={deletePlanTarget !== null}
                processing={deletingPlanId !== null}
                title="Eliminar plan de la importación"
                onConfirm={executeDeletePlan}
                onOpenChange={(open) => {
                    if (!open && deletingPlanId === null) {
                        setDeletePlanTarget(null);
                    }
                }}
            >
                {deletePlanTarget ? (
                    <p className="text-muted-foreground text-xs">
                        Correo: <span className="font-mono text-foreground">{deletePlanTarget.email_hint}</span> · #
                        CSV {deletePlanTarget.csv_record_index}
                    </p>
                ) : null}
            </ConfirmActionModal>

            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, descartar todo el grupo"
                confirmVariant="destructive"
                description="Se descartarán todos los registros pendientes asociados a este correo. No es posible deshacerlo en esta cola; para recuperarlos tendrías que importar de nuevo el archivo."
                open={discardGroupTarget !== null}
                processing={discardGroupProcessing}
                title="Descartar grupo completo"
                onConfirm={executeDiscardGroup}
                onOpenChange={(open) => {
                    if (!open && !discardGroupProcessing) {
                        setDiscardGroupTarget(null);
                    }
                }}
            >
                {discardGroupTarget ? (
                    <p className="text-muted-foreground text-xs">
                        <span className="font-mono text-foreground">{discardGroupTarget.email}</span> —{' '}
                        {discardGroupTarget.plans_count} plan
                        {discardGroupTarget.plans_count === 1 ? '' : 'es'} pendiente(s).
                    </p>
                ) : null}
            </ConfirmActionModal>

            <Dialog
                open={editingPlan !== null}
                onOpenChange={(open) => {
                    if (!open && !editForm.processing) {
                        closeEditPlan();
                    }
                }}
            >
                <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-lg">
                    <DialogHeader>
                        <DialogTitle>
                            Editar plan{' '}
                            {editingPlan ? (
                                <span className="tabular-nums">#{editingPlan.csv_record_index}</span>
                            ) : null}
                        </DialogTitle>
                        <DialogDescription>
                            Ajusta correo, persona, wallet, montos o fechas. Al guardar se recalculan la simulación de
                            intereses y el identificador derivado del registro.
                        </DialogDescription>
                    </DialogHeader>
                    <form className="space-y-4" onSubmit={submitEditPlan}>
                        <div className="grid gap-2">
                            <Label htmlFor="edit_email_hint">Correo</Label>
                            <Input
                                id="edit_email_hint"
                                autoComplete="email"
                                name="email_hint"
                                required
                                type="email"
                                value={editForm.data.email_hint}
                                onChange={(e) => editForm.setData('email_hint', e.target.value)}
                                disabled={editForm.processing}
                            />
                            <InputError message={editForm.errors.email_hint} />
                        </div>
                        <div className="grid gap-3 sm:grid-cols-2">
                            <div className="grid gap-2">
                                <Label htmlFor="edit_first_name">Nombre</Label>
                                <Input
                                    id="edit_first_name"
                                    name="first_name"
                                    value={editForm.data.first_name}
                                    onChange={(e) => editForm.setData('first_name', e.target.value)}
                                    disabled={editForm.processing}
                                />
                                <InputError message={editForm.errors.first_name} />
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="edit_last_name">Apellidos</Label>
                                <Input
                                    id="edit_last_name"
                                    name="last_name"
                                    value={editForm.data.last_name}
                                    onChange={(e) => editForm.setData('last_name', e.target.value)}
                                    disabled={editForm.processing}
                                />
                                <InputError message={editForm.errors.last_name} />
                            </div>
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit_contact_number">Teléfono</Label>
                            <Input
                                id="edit_contact_number"
                                inputMode="tel"
                                name="contact_number"
                                value={editForm.data.contact_number}
                                onChange={(e) => editForm.setData('contact_number', e.target.value)}
                                disabled={editForm.processing}
                            />
                            <InputError message={editForm.errors.contact_number} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit_country">País</Label>
                            <Select
                                value={editForm.data.country}
                                onValueChange={(v) => editForm.setData('country', v)}
                                disabled={editForm.processing}
                            >
                                <SelectTrigger id="edit_country" className="w-full">
                                    <SelectValue placeholder="País" />
                                </SelectTrigger>
                                <SelectContent>
                                    {countryOptions.map((option) => (
                                        <SelectItem key={option.value} value={option.value}>
                                            {option.label}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <InputError message={editForm.errors.country} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit_wallet_address">Wallet TRC20</Label>
                            <Input
                                id="edit_wallet_address"
                                className="font-mono text-xs"
                                name="wallet_address"
                                value={editForm.data.wallet_address}
                                onChange={(e) => editForm.setData('wallet_address', e.target.value)}
                                disabled={editForm.processing}
                            />
                            <InputError message={editForm.errors.wallet_address} />
                        </div>
                        <div className="grid gap-3 sm:grid-cols-2">
                            <div className="grid gap-2">
                                <Label htmlFor="edit_amount">Monto (USD)</Label>
                                <Input
                                    id="edit_amount"
                                    inputMode="decimal"
                                    min={0.01}
                                    name="amount"
                                    required
                                    step="0.01"
                                    type="number"
                                    value={editForm.data.amount}
                                    onChange={(e) => editForm.setData('amount', e.target.value)}
                                    disabled={editForm.processing}
                                />
                                <InputError message={editForm.errors.amount} />
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="edit_duration">Duración (meses)</Label>
                                <Input
                                    id="edit_duration"
                                    max={1200}
                                    min={1}
                                    name="duration_months"
                                    required
                                    type="number"
                                    value={editForm.data.duration_months}
                                    onChange={(e) =>
                                        editForm.setData('duration_months', Number.parseInt(e.target.value, 10) || 1)
                                    }
                                    disabled={editForm.processing}
                                />
                                <InputError message={editForm.errors.duration_months} />
                            </div>
                        </div>
                        <div className="grid gap-3 sm:grid-cols-2">
                            <div className="grid gap-2">
                                <Label htmlFor="edit_confirmed_at">Inicio</Label>
                                <Input
                                    id="edit_confirmed_at"
                                    name="confirmed_at"
                                    type="date"
                                    value={editForm.data.confirmed_at}
                                    onChange={(e) => editForm.setData('confirmed_at', e.target.value)}
                                    disabled={editForm.processing}
                                />
                                <InputError message={editForm.errors.confirmed_at} />
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="edit_maturity_at">Vencimiento</Label>
                                <Input
                                    id="edit_maturity_at"
                                    name="maturity_at"
                                    type="date"
                                    value={editForm.data.maturity_at}
                                    onChange={(e) => editForm.setData('maturity_at', e.target.value)}
                                    disabled={editForm.processing}
                                />
                                <InputError message={editForm.errors.maturity_at} />
                            </div>
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="edit_monthly_return">% mensual</Label>
                            <Input
                                id="edit_monthly_return"
                                inputMode="decimal"
                                max={100}
                                min={0}
                                name="monthly_return_snapshot"
                                required
                                step="0.01"
                                type="number"
                                value={editForm.data.monthly_return_snapshot}
                                onChange={(e) => editForm.setData('monthly_return_snapshot', e.target.value)}
                                disabled={editForm.processing}
                            />
                            <InputError message={editForm.errors.monthly_return_snapshot} />
                        </div>
                        <DialogFooter className="gap-2 sm:gap-0">
                            <Button
                                disabled={editForm.processing}
                                onClick={closeEditPlan}
                                type="button"
                                variant="ghost"
                            >
                                Cancelar
                            </Button>
                            <Button disabled={editForm.processing} type="submit">
                                {editForm.processing ? (
                                    <>
                                        <Loader2 className="mr-2 size-4 animate-spin" />
                                        Guardando…
                                    </>
                                ) : (
                                    'Guardar cambios'
                                )}
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            <Head title="Importación — revisión" />

            <div className="space-y-8">
                <div>
                    <h1 className="text-3xl font-bold tracking-tight">
                        Importación — revisión por usuario
                    </h1>
                    <p className="text-muted-foreground mt-1 max-w-3xl text-sm">
                        Revisa y aprueba por usuario los registros pendientes de importación.
                    </p>
                </div>

                <div className="text-muted-foreground flex flex-wrap items-center gap-x-4 gap-y-1 text-sm">
                    <span className="flex items-center gap-2">
                        <FileWarning className="size-4 shrink-0" />
                        <span>
                            Grupos:{' '}
                            <strong className="text-foreground tabular-nums">
                                {groups_count}
                            </strong>
                        </span>
                    </span>
                    <span>
                        Registros pendientes:{' '}
                        <strong className="text-foreground tabular-nums">
                            {pending_count}
                        </strong>
                    </span>
                </div>

                <Separator />

                {groups.length === 0 ? (
                    <p className="text-muted-foreground text-sm">
                        No hay registros pendientes.
                    </p>
                ) : (
                    <div className="space-y-8">
                        {groups.map((group) => (
                            <Card key={group.email_key}>
                                <CardHeader className="pb-3">
                                    <div className="flex flex-wrap items-start justify-between gap-3">
                                        <div>
                                            <CardTitle className="text-base font-mono text-sm">
                                                {group.email}
                                            </CardTitle>
                                            <CardDescription className="mt-1">
                                                {group.is_new_user ? (
                                                    <span className="text-amber-600 dark:text-amber-500">
                                                        Usuario nuevo al aprobar
                                                    </span>
                                                ) : (
                                                    <>
                                                        Usuario existente
                                                        {group.existing_user
                                                            ? ` · ID ${group.existing_user.id} · KYC ${group.existing_user.kyc_status}`
                                                            : null}
                                                    </>
                                                )}
                                            </CardDescription>
                                        </div>
                                        <div className="flex flex-wrap gap-2">
                                            <Button
                                                disabled={approvingEmail === group.email}
                                                onClick={() => requestApprove(group)}
                                                type="button"
                                            >
                                                {approvingEmail === group.email ? (
                                                    <>
                                                        <Loader2 className="mr-2 size-4 animate-spin" />
                                                        Aprobando…
                                                    </>
                                                ) : (
                                                    'Aprobar grupo'
                                                )}
                                            </Button>
                                            <Button
                                                disabled={discardingEmail === group.email}
                                                onClick={() => setDiscardGroupTarget(group)}
                                                type="button"
                                                variant="outline"
                                            >
                                                {discardingEmail === group.email ? (
                                                    <>
                                                        <Loader2 className="mr-2 size-4 animate-spin" />
                                                        …
                                                    </>
                                                ) : (
                                                    'Descartar grupo'
                                                )}
                                            </Button>
                                        </div>
                                    </div>
                                </CardHeader>
                                <CardContent className="space-y-6">
                                    <div>
                                        <h3 className="mb-2 text-sm font-medium">
                                            Datos propuestos (CSV)
                                        </h3>
                                        <dl className="grid gap-2 text-sm sm:grid-cols-2 lg:grid-cols-3">
                                            <div>
                                                <dt className="text-muted-foreground">Nombre</dt>
                                                <dd>
                                                    {[group.proposed.first_name, group.proposed.last_name]
                                                        .filter(Boolean)
                                                        .join(' ') || '—'}
                                                </dd>
                                            </div>
                                            <div>
                                                <dt className="text-muted-foreground">Teléfono</dt>
                                                <dd>{group.proposed.contact_number ?? '—'}</dd>
                                            </div>
                                            <div>
                                                <dt className="text-muted-foreground">País</dt>
                                                <dd>{group.proposed.country ?? '—'}</dd>
                                            </div>
                                            <div className="sm:col-span-2 lg:col-span-3">
                                                <dt className="text-muted-foreground">
                                                    Wallet TRC20 (CSV)
                                                </dt>
                                                <dd className="font-mono text-xs break-all">
                                                    {group.proposed.wallet_address ?? '—'}
                                                </dd>
                                            </div>
                                        </dl>
                                    </div>

                                    {!group.is_new_user && group.portfolio ? (
                                        <div>
                                            <h3 className="mb-2 text-sm font-medium">
                                                Cartera actual en la plataforma
                                            </h3>
                                            <dl className="grid gap-2 text-sm sm:grid-cols-2 lg:grid-cols-3">
                                                <div>
                                                    <dt className="text-muted-foreground">
                                                        Retirable (ledger)
                                                    </dt>
                                                    <dd className="tabular-nums font-medium">
                                                        $ {formatUsd(group.portfolio.withdrawable_usd)}
                                                    </dd>
                                                </div>
                                                <div>
                                                    <dt className="text-muted-foreground">
                                                        Principal en contratos (activos)
                                                    </dt>
                                                    <dd className="tabular-nums font-medium">
                                                        ${' '}
                                                        {formatUsd(
                                                            group.portfolio.principal_locked_usd,
                                                        )}
                                                    </dd>
                                                </div>
                                                <div>
                                                    <dt className="text-muted-foreground">
                                                        Capital en contratos (capital_balance)
                                                    </dt>
                                                    <dd className="tabular-nums font-medium">
                                                        ${' '}
                                                        {formatUsd(
                                                            group.portfolio.capital_in_contracts_usd,
                                                        )}
                                                    </dd>
                                                </div>
                                                <div>
                                                    <dt className="text-muted-foreground">
                                                        Inversiones activas / pendientes
                                                    </dt>
                                                    <dd className="tabular-nums">
                                                        {group.portfolio.active_investments} /{' '}
                                                        {group.portfolio.pending_investments}
                                                    </dd>
                                                </div>
                                            </dl>
                                        </div>
                                    ) : null}

                                    <Alert className="border-amber-500/40 bg-amber-50/80 dark:bg-amber-950/25">
                                        <AlertTitle className="text-sm">
                                            Intereses desde la fecha de inicio
                                        </AlertTitle>
                                        <AlertDescription className="text-xs">
                                            {accrualModeSummary(group)} Al aprobar se registrarán movimientos
                                            atrasados hasta el{' '}
                                            <strong>{group.accrual_group.cutoff_date}</strong> (misma fórmula que la
                                            acreditación configurada en el sistema). Ganancia simulada en este grupo:{' '}
                                            <strong className="text-foreground tabular-nums">
                                                $ {formatUsd(group.accrual_group.total_gain_usd)}
                                            </strong>
                                            . Revisa el detalle por plan en la tabla.
                                        </AlertDescription>
                                    </Alert>

                                    <div>
                                        <div className="mb-2 flex flex-wrap items-baseline justify-between gap-2">
                                            <h3 className="text-sm font-medium">
                                                Planes a crear ({group.plans_count})
                                            </h3>
                                            <p className="text-muted-foreground text-sm tabular-nums">
                                                Nuevo principal total:{' '}
                                                <strong className="text-foreground">
                                                    $ {formatUsd(group.new_principal_total_usd)}
                                                </strong>
                                            </p>
                                        </div>
                                        <div className="overflow-x-auto rounded-md border">
                                            <table className="w-full min-w-[1000px] text-left text-sm">
                                                <thead>
                                                    <tr className="text-muted-foreground border-b">
                                                        <th className="px-3 py-2 text-right font-medium whitespace-nowrap">
                                                            Acciones
                                                        </th>
                                                        <th className="px-3 py-2 font-medium">
                                                            # CSV
                                                        </th>
                                                        <th className="px-3 py-2 text-right font-medium">
                                                            Monto
                                                        </th>
                                                        <th className="px-3 py-2 font-medium">
                                                            Dur.
                                                        </th>
                                                        <th className="px-3 py-2 font-medium">
                                                            Inicio
                                                        </th>
                                                        <th className="px-3 py-2 font-medium">
                                                            Vence
                                                        </th>
                                                        <th className="px-3 py-2 text-right font-medium">
                                                            % mes
                                                        </th>
                                                        <th className="px-3 py-2 text-right font-medium">
                                                            Intereses sim.
                                                        </th>
                                                        <th className="px-3 py-2 text-right font-medium">
                                                            Saldo sim.
                                                        </th>
                                                        <th className="px-3 py-2 font-medium">
                                                            CSV gan./disp.
                                                        </th>
                                                        <th className="px-3 py-2 font-medium">
                                                            CSV bloq.
                                                        </th>
                                                        <th className="px-3 py-2 font-medium">
                                                            CSV total
                                                        </th>
                                                    </tr>
                                                </thead>
                                                <tbody className="divide-y">
                                                    {group.plans.map((plan) => (
                                                        <tr key={plan.id}>
                                                            <td className="px-3 py-2 text-right">
                                                                <div className="flex justify-end gap-0.5">
                                                                    <Button
                                                                        aria-label={`Editar plan ${plan.csv_record_index}`}
                                                                        className="size-8"
                                                                        disabled={
                                                                            editForm.processing &&
                                                                            editingPlan?.id === plan.id
                                                                        }
                                                                        onClick={() => openEditPlan(plan)}
                                                                        size="icon"
                                                                        type="button"
                                                                        variant="ghost"
                                                                    >
                                                                        <Pencil className="size-4" />
                                                                    </Button>
                                                                    <Button
                                                                        aria-label={`Eliminar plan ${plan.csv_record_index}`}
                                                                        className="text-destructive hover:text-destructive size-8"
                                                                        disabled={deletingPlanId === plan.id}
                                                                        onClick={() => setDeletePlanTarget(plan)}
                                                                        size="icon"
                                                                        type="button"
                                                                        variant="ghost"
                                                                    >
                                                                        {deletingPlanId === plan.id ? (
                                                                            <Loader2 className="size-4 animate-spin" />
                                                                        ) : (
                                                                            <Trash2 className="size-4" />
                                                                        )}
                                                                    </Button>
                                                                </div>
                                                            </td>
                                                            <td className="px-3 py-2 tabular-nums">
                                                                {plan.csv_record_index}
                                                            </td>
                                                            <td className="px-3 py-2 text-right tabular-nums">
                                                                $ {formatUsd(plan.amount)}
                                                            </td>
                                                            <td className="px-3 py-2">
                                                                {plan.duration_months} m
                                                            </td>
                                                            <td className="px-3 py-2 whitespace-nowrap">
                                                                {formatDateShort(
                                                                    plan.confirmed_at,
                                                                )}
                                                            </td>
                                                            <td className="px-3 py-2 whitespace-nowrap">
                                                                {formatDateShort(
                                                                    plan.maturity_at,
                                                                )}
                                                            </td>
                                                            <td className="px-3 py-2 text-right tabular-nums">
                                                                {plan.monthly_return_snapshot}
                                                                %
                                                            </td>
                                                            <td className="px-3 py-2 text-right tabular-nums">
                                                                ${' '}
                                                                {formatUsd(plan.accrual_preview.total_gain_usd)}
                                                            </td>
                                                            <td className="px-3 py-2 text-right tabular-nums">
                                                                ${' '}
                                                                {formatUsd(plan.accrual_preview.final_balance_usd)}
                                                            </td>
                                                            <td className="max-w-[140px] truncate px-3 py-2 text-xs">
                                                                {plan.csv_saldo_ganancias ?? '—'}
                                                            </td>
                                                            <td className="max-w-[120px] truncate px-3 py-2 text-xs">
                                                                {plan.csv_saldo_bloqueado ?? '—'}
                                                            </td>
                                                            <td className="max-w-[120px] truncate px-3 py-2 text-xs">
                                                                {plan.csv_saldo_total ?? '—'}
                                                            </td>
                                                        </tr>
                                                    ))}
                                                </tbody>
                                            </table>
                                        </div>
                                        <div className="mt-4 space-y-2">
                                            <h4 className="text-muted-foreground text-xs font-medium">
                                                Simulación mes a mes (por plan)
                                            </h4>
                                            {group.plans.map((plan) =>
                                                plan.accrual_preview.lines.length > 0 ? (
                                                    <details
                                                        key={`accrual-${plan.id}`}
                                                        className="rounded-md border text-xs"
                                                    >
                                                        <summary className="cursor-pointer px-3 py-2 font-medium">
                                                            Plan #{plan.csv_record_index} ·{' '}
                                                            {plan.accrual_preview.lines.length} período(s) · +$
                                                            {formatUsd(plan.accrual_preview.total_gain_usd)}
                                                        </summary>
                                                        <div className="overflow-x-auto border-t">
                                                            <table className="w-full min-w-[520px] text-left">
                                                                <thead>
                                                                    <tr className="text-muted-foreground border-b">
                                                                        <th className="px-3 py-1.5">
                                                                            Periodo
                                                                        </th>
                                                                        <th className="px-3 py-1.5">Cierre</th>
                                                                        <th className="px-3 py-1.5">Desde</th>
                                                                        <th className="px-3 py-1.5">Hasta</th>
                                                                        <th className="px-3 py-1.5 text-right">
                                                                            Interés
                                                                        </th>
                                                                        <th className="px-3 py-1.5 text-right">
                                                                            Saldo
                                                                        </th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody className="divide-y">
                                                                    {plan.accrual_preview.lines.map((line, idx) => (
                                                                        <tr key={`${plan.id}-line-${idx}`}>
                                                                            <td className="px-3 py-1.5 capitalize">
                                                                                {line.month_label}
                                                                            </td>
                                                                            <td className="px-3 py-1.5 whitespace-nowrap">
                                                                                {line.accrual_run_date ?? '—'}
                                                                            </td>
                                                                            <td className="px-3 py-1.5 whitespace-nowrap">
                                                                                {line.period_start}
                                                                            </td>
                                                                            <td className="px-3 py-1.5 whitespace-nowrap">
                                                                                {line.period_end}
                                                                            </td>
                                                                            <td className="px-3 py-1.5 text-right tabular-nums">
                                                                                $ {formatUsd(line.gain_usd)}
                                                                            </td>
                                                                            <td className="px-3 py-1.5 text-right tabular-nums">
                                                                                $ {formatUsd(line.balance_after)}
                                                                            </td>
                                                                        </tr>
                                                                    ))}
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    </details>
                                                ) : (
                                                    <p
                                                        key={`no-accrual-${plan.id}`}
                                                        className="text-muted-foreground px-1 text-xs"
                                                    >
                                                        Plan #{plan.csv_record_index}: sin intereses simulados en el
                                                        rango (fecha futura o % en cero).
                                                    </p>
                                                ),
                                            )}
                                        </div>
                                    </div>
                                </CardContent>
                            </Card>
                        ))}
                    </div>
                )}

                <Button asChild variant="outline">
                    <Link href="/admin" prefetch>
                        ← Panel administrativo
                    </Link>
                </Button>
            </div>
        </>
    );
}

ForexImportStaging.layout = {
    breadcrumbs: [
        { title: 'Administración', href: '/admin' },
        { title: 'Importación', href: '/admin/importacion-forex' },
    ],
};
