import { Head, Link, useForm } from '@inertiajs/react';
import { ArrowLeft, Loader2, RefreshCw, Trash2 } from 'lucide-react';
import { useCallback, useState } from 'react';
import { ConfirmActionModal } from '@/components/confirm-action-modal';
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 { cn } from '@/lib/utils';

type RunMeta = {
    date: string;
    mode: 'daily' | 'period';
    mode_label: string;
    tx_count: number;
    investments_distinct: number;
    total_gain: string;
    referral_count: number;
    total_referral: string;
};

type GainLine = {
    id: number;
    investment_id: number;
    investor_name: string;
    investor_email: string | null;
    txid: string;
    principal_usd: string | null;
    plan_percent: string | null;
    amount_usd: string;
    balance_after_usd: string | null;
    applied_percent_label: string | null;
    gain_period_start: string | null;
    gain_period_end: string | null;
};

type ReferralLine = {
    id: number;
    level: number | null;
    type: string;
    beneficiary_name: string;
    beneficiary_email: string | null;
    source_txid: string | null;
    amount_usd: string;
};

type RecalcSnapshot = {
    gain_usd: string;
    plan_percent: string;
    applied_percent_label: string | null;
    period_start: string | null;
    period_end: string | null;
    period_label: string | null;
    balance_after_usd: string | null;
    investment_capital_usd: string;
    user_ledger_balance_usd: string;
};

type RecalcPreview = {
    needs_change: boolean;
    reason?: string;
    transaction_id: number;
    investment_id: number;
    txid: string;
    is_imported: boolean;
    investor_name: string;
    investor_email: string | null;
    current: RecalcSnapshot;
    proposed: RecalcSnapshot;
    delta: {
        gain_usd: string;
        investment_capital_usd: string;
        user_ledger_balance_usd: string;
    };
};

type Props = {
    adjustments_enabled?: boolean;
    run: RunMeta;
    lines: GainLine[];
    referral_lines: ReferralLine[];
};

function formatDate(iso: string): string {
    try {
        return new Intl.DateTimeFormat('es', { dateStyle: 'long' }).format(new Date(iso));
    } catch {
        return iso;
    }
}

function referralTypeLabel(type: string): string {
    if (type === 'referral_direct_bonus') return 'Directo';
    if (type === 'referral_indirect_bonus') return 'Indirecto';
    return type;
}

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

function RecalcComparisonRow({
    label,
    current,
    proposed,
    highlight = false,
}: {
    label: string;
    current: string | null;
    proposed: string | null;
    highlight?: boolean;
}) {
    const changed = (current ?? '') !== (proposed ?? '');

    return (
        <tr className={cn(changed && 'bg-amber-500/5')}>
            <td className="px-3 py-2 font-medium text-muted-foreground">{label}</td>
            <td className="px-3 py-2 tabular-nums">{current ?? '—'}</td>
            <td
                className={cn(
                    'px-3 py-2 tabular-nums',
                    changed && (highlight ? 'font-semibold text-primary' : 'font-medium'),
                )}
            >
                {proposed ?? '—'}
            </td>
        </tr>
    );
}

export default function PlatformMonthlyAccrualDetail({
    run,
    lines,
    referral_lines,
    adjustments_enabled = false,
}: Props) {
    const indexHref = '/admin/acreditacion-mensual';
    const [voidConfirmOpen, setVoidConfirmOpen] = useState(false);
    const voidForm = useForm({ mode: run.mode });

    const canVoidRun =
        adjustments_enabled && run.mode === 'period' && run.tx_count > 0;

    const canRecalculate = adjustments_enabled && run.mode === 'period';

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

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

    const openRecalcModal = useCallback(async (line: GainLine) => {
        setRecalcTarget(line);
        setRecalcPreview(null);
        setRecalcError(null);
        setRecalcLoading(true);

        try {
            const response = await fetch(
                `/admin/acreditacion-mensual/movimientos/${line.id}/recalcular`,
                {
                    headers: { Accept: 'application/json' },
                    credentials: 'same-origin',
                },
            );

            if (!response.ok) {
                throw new Error('No se pudo cargar la vista previa del recálculo.');
            }

            const data = (await response.json()) as RecalcPreview;
            setRecalcPreview(data);
        } catch {
            setRecalcError('No se pudo cargar la vista previa del recálculo.');
        } finally {
            setRecalcLoading(false);
        }
    }, []);

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

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

    const runGainAfterApply =
        recalcPreview?.needs_change && recalcTarget
            ? (() => {
                  const currentTotal = Number.parseFloat(run.total_gain);
                  const delta = Number.parseFloat(recalcPreview.delta.gain_usd);
                  if (!Number.isFinite(currentTotal) || !Number.isFinite(delta)) {
                      return null;
                  }
                  return (currentTotal + delta).toFixed(2);
              })()
            : null;

    function executeVoidRun() {
        voidForm.post(`/admin/acreditacion-mensual/${run.date}/anular`, {
            preserveScroll: true,
            onSuccess: () => setVoidConfirmOpen(false),
        });
    }

    return (
        <>
            <Head title={`Acreditación ${run.date}`} />

            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, anular ejecución"
                confirmVariant="destructive"
                description="Elimina todas las ganancias de esta entrega y las comisiones de referidos generadas por ellas. Solo disponible en modo debug."
                open={voidConfirmOpen}
                processing={voidForm.processing}
                title={`¿Anular acreditación del ${formatDate(run.date)}?`}
                onConfirm={executeVoidRun}
                onOpenChange={setVoidConfirmOpen}
            >
                <div className="space-y-2 text-sm text-muted-foreground">
                    <p>
                        <span className="font-medium text-foreground">Ganancias:</span>{' '}
                        {run.tx_count} movimiento(s) · US$ {run.total_gain}
                    </p>
                    <p>
                        <span className="font-medium text-foreground">Referidos:</span>{' '}
                        {run.referral_count} comisión(es) · US$ {run.total_referral}
                    </p>
                </div>
            </ConfirmActionModal>

            <Dialog
                open={recalcTarget !== null}
                onOpenChange={(open) => !open && closeRecalcModal()}
            >
                <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
                    <DialogHeader>
                        <DialogTitle>Recalcular acreditación</DialogTitle>
                        <DialogDescription className="text-left">
                            Ajuste según el % pactado de la inversión y el mes calendario de la
                            fecha de ejecución ({run.date}).
                        </DialogDescription>
                    </DialogHeader>

                    {recalcTarget ? (
                        <div className="text-muted-foreground space-y-1 text-sm">
                            <p>
                                <span className="text-foreground font-medium">Inversionista:</span>{' '}
                                {recalcPreview?.investor_name ?? recalcTarget.investor_name}
                            </p>
                            <p className="font-mono text-xs break-all">
                                TXID: {recalcPreview?.txid ?? recalcTarget.txid}
                            </p>
                            {recalcPreview?.is_imported ? (
                                <Badge variant="outline" className="mt-1 text-xs font-normal">
                                    Importada FOREX
                                </Badge>
                            ) : null}
                        </div>
                    ) : null}

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

                    {!recalcLoading && recalcError ? (
                        <p className="text-destructive py-4 text-sm">{recalcError}</p>
                    ) : null}

                    {!recalcLoading && recalcPreview && !recalcPreview.needs_change ? (
                        <Alert>
                            <AlertTitle>Sin cambios</AlertTitle>
                            <AlertDescription>
                                {recalcPreview.reason ??
                                    'Esta fila ya coincide con el período y % pactado esperados.'}
                            </AlertDescription>
                        </Alert>
                    ) : null}

                    {!recalcLoading &&
                    recalcPreview?.needs_change &&
                    recalcPreview.current &&
                    recalcPreview.proposed ? (
                        <div className="space-y-4">
                            <div className="overflow-x-auto rounded-md border">
                                <table className="w-full min-w-[520px] text-left text-sm">
                                    <thead>
                                        <tr className="border-b bg-muted/40 text-muted-foreground">
                                            <th className="px-3 py-2 font-medium">Campo</th>
                                            <th className="px-3 py-2 font-medium">Actual</th>
                                            <th className="px-3 py-2 font-medium">Propuesto</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y">
                                        <RecalcComparisonRow
                                            current={recalcPreview.current.period_label}
                                            label="Período contractual"
                                            proposed={recalcPreview.proposed.period_label}
                                        />
                                        <RecalcComparisonRow
                                            current={
                                                recalcPreview.current.period_start &&
                                                recalcPreview.current.period_end
                                                    ? `${recalcPreview.current.period_start} → ${recalcPreview.current.period_end}`
                                                    : null
                                            }
                                            label="Rango fechas"
                                            proposed={
                                                recalcPreview.proposed.period_start &&
                                                recalcPreview.proposed.period_end
                                                    ? `${recalcPreview.proposed.period_start} → ${recalcPreview.proposed.period_end}`
                                                    : null
                                            }
                                        />
                                        <RecalcComparisonRow
                                            current={`${recalcPreview.current.plan_percent}%`}
                                            label="% plan pactado"
                                            proposed={`${recalcPreview.proposed.plan_percent}%`}
                                        />
                                        <RecalcComparisonRow
                                            current={
                                                recalcPreview.current.applied_percent_label
                                            }
                                            label="% otorgado"
                                            proposed={
                                                recalcPreview.proposed.applied_percent_label
                                            }
                                        />
                                        <RecalcComparisonRow
                                            current={`${recalcPreview.current.gain_usd} US$`}
                                            highlight
                                            label="Ganancia"
                                            proposed={`${recalcPreview.proposed.gain_usd} US$`}
                                        />
                                        <RecalcComparisonRow
                                            current={
                                                recalcPreview.current.balance_after_usd
                                                    ? `${recalcPreview.current.balance_after_usd} US$`
                                                    : null
                                            }
                                            label="Capital tras movimiento"
                                            proposed={
                                                recalcPreview.proposed.balance_after_usd
                                                    ? `${recalcPreview.proposed.balance_after_usd} US$`
                                                    : null
                                            }
                                        />
                                        <RecalcComparisonRow
                                            current={`${recalcPreview.current.investment_capital_usd} US$`}
                                            label="Capital inversión (total)"
                                            proposed={`${recalcPreview.proposed.investment_capital_usd} US$`}
                                        />
                                        <RecalcComparisonRow
                                            current={`${recalcPreview.current.user_ledger_balance_usd} US$`}
                                            label="Balance usuario (libro)"
                                            proposed={`${recalcPreview.proposed.user_ledger_balance_usd} US$`}
                                        />
                                    </tbody>
                                </table>
                            </div>

                            <div className="rounded-md border bg-muted/30 px-4 py-3 text-sm">
                                <p className="font-medium">Impacto del ajuste</p>
                                <ul className="text-muted-foreground mt-2 space-y-1 tabular-nums">
                                    <li>
                                        Ganancia fila:{' '}
                                        <span className="text-foreground font-medium">
                                            {formatDelta(recalcPreview.delta.gain_usd)} US$
                                        </span>
                                    </li>
                                    <li>
                                        Capital inversión:{' '}
                                        <span className="text-foreground font-medium">
                                            {formatDelta(
                                                recalcPreview.delta.investment_capital_usd,
                                            )}{' '}
                                            US$
                                        </span>
                                    </li>
                                    <li>
                                        Balance usuario:{' '}
                                        <span className="text-foreground font-medium">
                                            {formatDelta(
                                                recalcPreview.delta.user_ledger_balance_usd,
                                            )}{' '}
                                            US$
                                        </span>
                                    </li>
                                    {runGainAfterApply !== null ? (
                                        <li>
                                            Total ganancia ejecución:{' '}
                                            <span className="text-foreground font-medium">
                                                {run.total_gain} → {runGainAfterApply} US$
                                            </span>
                                        </li>
                                    ) : null}
                                </ul>
                            </div>
                        </div>
                    ) : null}

                    <DialogFooter className="gap-2 sm:gap-0">
                        <Button
                            disabled={recalcForm.processing}
                            type="button"
                            variant="ghost"
                            onClick={closeRecalcModal}
                        >
                            Cancelar
                        </Button>
                        <Button
                            disabled={
                                recalcLoading ||
                                recalcForm.processing ||
                                !recalcPreview?.needs_change
                            }
                            type="button"
                            onClick={applyRecalculation}
                        >
                            {recalcForm.processing ? (
                                <>
                                    <Loader2 className="size-4 animate-spin" />
                                    Aplicando…
                                </>
                            ) : (
                                'Aplicar ajuste'
                            )}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <div className="mx-auto max-w-6xl space-y-6 p-4">
                <div className="flex flex-wrap items-center gap-3">
                    <Link
                        className="text-muted-foreground hover:text-foreground inline-flex items-center gap-2 text-sm"
                        href={indexHref}
                    >
                        <ArrowLeft className="size-4" />
                        Historial de acreditaciones
                    </Link>
                </div>

                <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
                    <div>
                        <h1 className="text-2xl font-bold tracking-tight sm:text-3xl">
                            Detalle de ejecución
                        </h1>
                        <p className="text-muted-foreground mt-2 text-sm">
                            {formatDate(run.date)} · {run.mode_label}
                        </p>
                    </div>
                    {canVoidRun ? (
                        <Button
                            type="button"
                            variant="outline"
                            className="shrink-0 text-destructive hover:text-destructive"
                            onClick={() => setVoidConfirmOpen(true)}
                        >
                            <Trash2 className="size-4" aria-hidden />
                            Anular ejecución
                        </Button>
                    ) : null}
                </div>

                {canVoidRun ? (
                    <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">
                            Puede anular toda esta entrega mensual (ganancias + comisiones de referidos)
                            y volver a ejecutarla desde Acreditaciones → Acreditación manual.
                        </AlertDescription>
                    </Alert>
                ) : null}

                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Movimientos</CardDescription>
                            <CardTitle className="text-2xl tabular-nums">{run.tx_count}</CardTitle>
                        </CardHeader>
                    </Card>
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Inversiones</CardDescription>
                            <CardTitle className="text-2xl tabular-nums">
                                {run.investments_distinct}
                            </CardTitle>
                        </CardHeader>
                    </Card>
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Ganancia acreditada</CardDescription>
                            <CardTitle className="text-2xl tabular-nums">
                                {run.total_gain} US$
                            </CardTitle>
                        </CardHeader>
                    </Card>
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Comisiones referidos</CardDescription>
                            <CardTitle className="text-2xl tabular-nums">
                                {run.total_referral} US$
                            </CardTitle>
                            <CardDescription className="text-xs">
                                {run.referral_count} movimiento(s)
                            </CardDescription>
                        </CardHeader>
                    </Card>
                </div>

                <Card>
                    <CardHeader>
                        <CardTitle>Entregado por inversión</CardTitle>
                        <CardDescription>
                            Cada fila es lo registrado en el libro al ejecutar la acreditación: monto,
                            capital tras el movimiento y % mensual efectivo aplicado ese día.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="overflow-x-auto p-0">
                        {lines.length === 0 ? (
                            <p className="text-muted-foreground p-8 text-center text-sm">
                                No hay movimientos para esta fecha y modo.
                            </p>
                        ) : (
                            <table className="w-full min-w-[960px] text-left text-sm">
                                <thead>
                                    <tr className="border-b bg-muted/40 text-muted-foreground">
                                        <th className="px-4 py-3 font-medium">Inversionista</th>
                                        <th className="px-4 py-3 font-medium">TXID</th>
                                        <th className="px-4 py-3 font-medium tabular-nums">
                                            Principal
                                        </th>
                                        <th className="px-4 py-3 font-medium tabular-nums">
                                            % plan
                                        </th>
                                        <th className="px-4 py-3 font-medium tabular-nums">
                                            % otorgado
                                        </th>
                                        <th className="px-4 py-3 font-medium tabular-nums">
                                            Ganancia
                                        </th>
                                        <th className="px-4 py-3 font-medium tabular-nums">
                                            Capital después
                                        </th>
                                        {run.mode === 'period' ? (
                                            <th className="px-4 py-3 font-medium">Período ganancia</th>
                                        ) : null}
                                        {canRecalculate ? (
                                            <th className="px-4 py-3 font-medium w-12">
                                                <span className="sr-only">Recalcular</span>
                                            </th>
                                        ) : null}
                                    </tr>
                                </thead>
                                <tbody className="divide-y">
                                    {lines.map((line) => (
                                        <tr key={line.id}>
                                            <td className="px-4 py-3">
                                                <div className="font-medium">{line.investor_name}</div>
                                                {line.investor_email ? (
                                                    <div className="text-muted-foreground text-xs">
                                                        {line.investor_email}
                                                    </div>
                                                ) : null}
                                            </td>
                                            <td className="max-w-[140px] truncate px-4 py-3 font-mono text-xs">
                                                {line.txid}
                                            </td>
                                            <td className="px-4 py-3 tabular-nums">
                                                {line.principal_usd ?? '—'} US$
                                            </td>
                                            <td className="px-4 py-3 tabular-nums text-muted-foreground">
                                                {line.plan_percent != null
                                                    ? `${line.plan_percent}%`
                                                    : '—'}
                                            </td>
                                            <td className="px-4 py-3 text-xs tabular-nums">
                                                {line.applied_percent_label ?? '—'}
                                            </td>
                                            <td className="px-4 py-3 font-medium tabular-nums text-primary">
                                                {line.amount_usd} US$
                                            </td>
                                            <td className="px-4 py-3 tabular-nums">
                                                {line.balance_after_usd != null
                                                    ? `${line.balance_after_usd} US$`
                                                    : '—'}
                                            </td>
                                            {run.mode === 'period' ? (
                                                <td className="whitespace-nowrap px-4 py-3 text-xs text-muted-foreground">
                                                    {line.gain_period_start && line.gain_period_end
                                                        ? `${line.gain_period_start} → ${line.gain_period_end}`
                                                        : '—'}
                                                </td>
                                            ) : null}
                                            {canRecalculate ? (
                                                <td className="px-4 py-3">
                                                    <Button
                                                        aria-label="Recalcular acreditación"
                                                        className="size-8"
                                                        size="icon"
                                                        type="button"
                                                        variant="ghost"
                                                        onClick={() => openRecalcModal(line)}
                                                    >
                                                        <RefreshCw className="size-4" />
                                                    </Button>
                                                </td>
                                            ) : null}
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        )}
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader>
                        <CardTitle>Comisiones de referidos generadas</CardTitle>
                        <CardDescription>
                            Bonos directos e indirectos disparados por las ganancias de esta ejecución.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="overflow-x-auto p-0">
                        {referral_lines.length === 0 ? (
                            <p className="text-muted-foreground p-8 text-center text-sm">
                                Esta ejecución no generó comisiones de referidos.
                            </p>
                        ) : (
                            <table className="w-full min-w-[720px] text-left text-sm">
                                <thead>
                                    <tr className="border-b bg-muted/40 text-muted-foreground">
                                        <th className="px-4 py-3 font-medium">Beneficiario</th>
                                        <th className="px-4 py-3 font-medium">Nivel</th>
                                        <th className="px-4 py-3 font-medium">Inversión origen</th>
                                        <th className="px-4 py-3 font-medium tabular-nums">Monto</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y">
                                    {referral_lines.map((line) => (
                                        <tr key={line.id}>
                                            <td className="px-4 py-3">
                                                <div className="font-medium">{line.beneficiary_name}</div>
                                                {line.beneficiary_email ? (
                                                    <div className="text-muted-foreground text-xs">
                                                        {line.beneficiary_email}
                                                    </div>
                                                ) : null}
                                            </td>
                                            <td className="px-4 py-3">
                                                <Badge variant="outline" className="text-xs font-normal">
                                                    {referralTypeLabel(line.type)}
                                                    {line.level != null ? ` · L${line.level}` : ''}
                                                </Badge>
                                            </td>
                                            <td className="max-w-[140px] truncate px-4 py-3 font-mono text-xs">
                                                {line.source_txid ?? '—'}
                                            </td>
                                            <td className="px-4 py-3 font-medium tabular-nums">
                                                {line.amount_usd} US$
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        )}
                    </CardContent>
                </Card>
            </div>
        </>
    );
}

PlatformMonthlyAccrualDetail.layout = {
    breadcrumbs: [
        { title: 'Administración', href: '/admin' },
        { title: 'Acreditaciones', href: '/admin/acreditacion-mensual' },
        { title: 'Detalle', href: '#' },
    ],
};
