import { Head, Link } from '@inertiajs/react';
import { ArrowLeft } from 'lucide-react';
import { useState } from 'react';
import {
    AppBackLinkRow,
    AppPage,
    AppPageHeader,
    AppPageTitleBlock,
} from '@/components/app-page';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { InertiaPaginatorFooter } from '@/components/inertia-paginator-footer';
import { dashboard } from '@/routes';

type LedgerRow = {
    id: number;
    type: string;
    amount_usd: string;
    balance_after_usd: string;
    investment_txid: string;
    created_at: string | null;
    applied_percent: string | null;
    reference_month_index: number | null;
    withdrawal_destination_label: string | null;
    withdrawal_destination_network: string | null;
    withdrawal_destination_address: string | null;
    withdrawal_payout_txid: string | null;
};

/** Laravel `LengthAwarePaginator::toArray()` (Inertia serializa igual). */
type PaginatedTransactions = {
    data: LedgerRow[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    from: number | null;
    to: number | null;
    prev_page_url: string | null;
    next_page_url: string | null;
};

type Props = { transactions: PaginatedTransactions };

function typeLabel(code: string): string {
    const map: Record<string, string> = {
        deposit: 'Depósito',
        monthly_gain: 'Acreditación mensual',
        withdrawal: 'Retiro',
        admin_adjustment: 'Ajuste administrativo',
        admin_adjustment_reversal: 'Reversión de ajuste',
        referral_direct_bonus: 'Bono referido directo',
        referral_indirect_bonus: 'Bono referido indirecto',
        daily_gain: 'Ganancia (diaria)',
        period_accrual: 'Ganancia (período)',
        balance_consolidation_credit: 'Consolidación de saldo',
        balance_consolidation_debit: 'Consolidación de saldo',
    };

    return map[code] ?? code;
}

function typeBadgeVariant(code: string): 'default' | 'secondary' | 'outline' {
    if (code === 'monthly_gain') return 'secondary';
    if (code === 'daily_gain' || code === 'period_accrual') return 'secondary';
    if (code === 'withdrawal') return 'outline';
    if (code.startsWith('referral_')) return 'secondary';
    return 'default';
}

function formatShortDatetime(iso: string | null): string {
    if (!iso) return '—';

    try {
        return new Intl.DateTimeFormat('es', {
            dateStyle: 'short',
            timeStyle: 'short',
        }).format(new Date(iso));
    } catch {
        return '—';
    }
}

function LedgerDetailModal({
    row,
    open,
    onOpenChange,
}: {
    row: LedgerRow | null;
    open: boolean;
    onOpenChange: (open: boolean) => void;
}) {
    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-h-[min(85vh,32rem)] overflow-y-auto sm:max-w-md">
                <DialogHeader className="text-left">
                    <DialogTitle>Movimiento #{row?.id ?? '—'}</DialogTitle>
                    <DialogDescription>
                        Detalle completo del asiento contable seleccionado.
                    </DialogDescription>
                </DialogHeader>

                {row ? (
                    <dl className="grid gap-3 text-sm">
                        <div className="grid gap-1">
                            <dt className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
                                Tipo
                            </dt>
                            <dd className="text-foreground">
                                <Badge
                                    variant={typeBadgeVariant(row.type)}
                                    className="font-normal text-xs"
                                >
                                    {typeLabel(row.type)}
                                </Badge>
                            </dd>
                        </div>
                        <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                            <div className="grid gap-1">
                                <dt className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
                                    Monto
                                </dt>
                                <dd className="tabular-nums font-medium">{row.amount_usd} US$</dd>
                            </div>
                            <div className="grid gap-1">
                                <dt className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
                                    Saldo después
                                </dt>
                                <dd className="tabular-nums text-muted-foreground">
                                    {row.balance_after_usd} US$
                                </dd>
                            </div>
                        </div>
                        <div className="grid gap-1">
                            <dt className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
                                Inversión Asociada
                            </dt>
                            <dd className="break-all font-mono text-xs">{row.investment_txid}</dd>
                        </div>
                        <div className="grid gap-1">
                            <dt className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
                                Fecha
                            </dt>
                            <dd className="tabular-nums text-muted-foreground">
                                {formatShortDatetime(row.created_at)}
                            </dd>
                        </div>

                        {row.type === 'withdrawal' ? (
                            <>
                                <div className="grid gap-1">
                                    <dt className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
                                        Destino
                                    </dt>
                                    <dd>
                                        {row.withdrawal_destination_network ?? '—'}
                                        {row.withdrawal_destination_label
                                            ? ` · ${row.withdrawal_destination_label}`
                                            : ''}
                                    </dd>
                                </div>
                                {row.withdrawal_destination_address ? (
                                    <div className="grid gap-1">
                                        <dt className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
                                            Dirección
                                        </dt>
                                        <dd className="break-all font-mono text-xs">
                                            {row.withdrawal_destination_address}
                                        </dd>
                                    </div>
                                ) : null}
                                {row.withdrawal_payout_txid ? (
                                    <div className="grid gap-1">
                                        <dt className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
                                            ID de la transacción de pago
                                        </dt>
                                        <dd className="break-all font-mono text-xs">
                                            {row.withdrawal_payout_txid}
                                        </dd>
                                    </div>
                                ) : null}
                            </>
                        ) : null}

                        {row.type === 'monthly_gain' ? (
                            <div className="grid gap-1">
                                <dt className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
                                    Referencia período
                                </dt>
                                <dd className="text-muted-foreground">
                                    {row.reference_month_index != null
                                        ? row.applied_percent != null
                                            ? `Mes ${row.reference_month_index} · ${row.applied_percent} % aplicado`
                                            : `Mes ${row.reference_month_index}`
                                        : '—'}
                                </dd>
                            </div>
                        ) : null}
                    </dl>
                ) : null}

                <div className="flex justify-end border-t pt-4">
                    <Button type="button" variant="secondary" size="sm" onClick={() => onOpenChange(false)}>
                        Cerrar
                    </Button>
                </div>
            </DialogContent>
        </Dialog>
    );
}

export default function BalanceMovementsPage({ transactions }: Props) {
    const [detail, setDetail] = useState<LedgerRow | null>(null);

    return (
        <>
            <Head title="Movimientos" />

            <AppPage>
                <AppBackLinkRow>
                    <Button asChild variant="ghost" size="sm">
                        <Link href="/balances">
                            <ArrowLeft className="size-4" />
                            Mis balances
                        </Link>
                    </Button>
                </AppBackLinkRow>

                <AppPageHeader className="sm:flex-row sm:items-end sm:justify-between">
                    <AppPageTitleBlock
                        title="Movimientos"
                        description="Historial único consolidado por todas tus inversiones: depósitos, acreditaciones mensuales y retiros del capital disponible en el libro de cada inversión."
                        descriptionClassName="text-sm"
                    />
                </AppPageHeader>

                <LedgerDetailModal row={detail} open={detail !== null} onOpenChange={(o) => !o && setDetail(null)} />

                <Card>
                    <CardHeader className="space-y-0 pb-3">
                        <CardTitle className="text-base">Movimientos ({transactions.total})</CardTitle>
                    </CardHeader>
                    <CardContent className="overflow-x-auto p-0">
                        {transactions.total === 0 ? (
                            <p className="p-6 text-center text-muted-foreground text-sm">
                                Todavía no hay movimientos contables registrados para tu cuenta.
                            </p>
                        ) : (
                            <>
                                <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-4 py-3 font-medium tabular-nums">ID</th>
                                            <th className="px-4 py-3 font-medium">Tipo</th>
                                            <th className="px-4 py-3 font-medium tabular-nums">Monto</th>
                                            <th className="px-4 py-3 font-medium tabular-nums hidden sm:table-cell">
                                                Saldo tras mov.
                                            </th>
                                            <th className="whitespace-nowrap px-4 py-3 font-medium">Fecha</th>
                                            <th className="px-4 py-3 text-right font-medium">Detalle</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-border">
                                        {transactions.data.map((t) => (
                                            <tr key={t.id} className="hover:bg-muted/30">
                                                <td className="px-4 py-2.5 tabular-nums font-mono font-medium">
                                                    #{t.id}
                                                </td>
                                                <td className="px-4 py-2.5">
                                                    <Badge
                                                        variant={typeBadgeVariant(t.type)}
                                                        className="px-1.5 py-0 font-normal text-[10px]"
                                                    >
                                                        {typeLabel(t.type)}
                                                    </Badge>
                                                </td>
                                                <td className="px-4 py-2.5 font-semibold tabular-nums">$ {t.amount_usd}</td>
                                                <td className="px-4 py-2.5 tabular-nums text-muted-foreground hidden sm:table-cell">
                                                   $ {t.balance_after_usd}
                                                </td>
                                                <td className="whitespace-nowrap px-4 py-2.5 text-muted-foreground">
                                                    {formatShortDatetime(t.created_at)}
                                                </td>
                                                <td className="px-4 py-2.5 text-right">
                                                    <Button
                                                        type="button"
                                                        variant="ghost"
                                                        size="sm"
                                                        className="-my-1 h-7 px-2 text-xs"
                                                        onClick={() => setDetail(t)}
                                                    >
                                                        Ver detalles
                                                    </Button>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>

                                <InertiaPaginatorFooter paginator={transactions} />
                            </>
                        )}
                    </CardContent>
                </Card>
            </AppPage>
        </>
    );
}

BalanceMovementsPage.layout = {
    breadcrumbs: [
        { title: 'Inicio', href: dashboard() },
        { title: 'Mis balances', href: '/balances' },
        { title: 'Movimientos', href: '/balances/movimientos' },
    ],
};
