import { Head, Link, router } from '@inertiajs/react';
import { ArrowLeft, Check, ClipboardList, XCircle } from 'lucide-react';
import { useState } from 'react';
import { cn } from '@/lib/utils';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { ConfirmActionModal } from '@/components/confirm-action-modal';
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 { Textarea } from '@/components/ui/textarea';

export type WithdrawalReqRow = {
    id: number;
    investment_id: number | null;
    amount_usd: string;
    status: string;
    created_at: string | null;
    processed_at: string | null;
    admin_note: string | null;
    /** Identificador de depósito de la inversión (no es el payout). */
    txid: string;
    investor_name: string;
    investor_email: string | null | undefined;
    capital_at_request_usd: string | null;
    processed_by_label: string;
    destination_network: string | null;
    destination_address: string | null;
    destination_label: string | null;
    payout_txid: string | null;
    /** Comentario opcional enviado por el inversionista. */
    requester_note: string | null;
};

type HistoryRow = {
    id: number;
    created_at: string | null;
    amount_usd: string;
    balance_after_usd: string;
    txid: string;
    investor_email: string | null | undefined;
    investor_name: string;
    via_request_id: number | null;
    via_request_status: string | null;
};

type TabId = 'solicitudes' | 'historial';

type Props = {
    tab: TabId;
    pending: WithdrawalReqRow[];
    recent: WithdrawalReqRow[];
    history_rows: HistoryRow[];
};

const TABS: { id: TabId; label: string }[] = [
    { id: 'solicitudes', label: 'Solicitudes' },
    { id: 'historial', label: 'Historial ejecutados' },
];

export default function WithdrawalRequests({ tab, pending, recent, history_rows }: Props) {
    const [rejecting, setRejecting] = useState<WithdrawalReqRow | null>(null);
    const [rejectNote, setRejectNote] = useState('');
    const [busyId, setBusyId] = useState<number | null>(null);
    const [approving, setApproving] = useState<WithdrawalReqRow | null>(null);
    const [payoutTxid, setPayoutTxid] = useState('');
    const [payoutTxidError, setPayoutTxidError] = useState<string | null>(null);
    const [approveSummaryOpen, setApproveSummaryOpen] = useState(false);
    const [rejectSummaryOpen, setRejectSummaryOpen] = useState(false);

    function navigate(nextTab: TabId) {
        router.get('/admin/retiros/solicitudes', { tab: nextTab }, { preserveState: true, preserveScroll: true });
    }

    function confirmApprove() {
        if (!approving) return;
        const trimmed = payoutTxid.trim();
        if (!trimmed) {
            setPayoutTxidError('El TXID del envío es obligatorio.');
            return;
        }

        setPayoutTxidError(null);
        setBusyId(approving.id);

        router.patch(
            `/admin/retiros/solicitudes/${approving.id}/aprobar`,
            { payout_txid: trimmed },
            {
                preserveScroll: true,
                onFinish: () => {
                    setBusyId(null);
                },
                onSuccess: () => {
                    setApproving(null);
                    setPayoutTxid('');
                    setPayoutTxidError(null);
                    setApproveSummaryOpen(false);
                },
                onError: (errors) => {
                    const raw = errors.payout_txid;
                    const msg = Array.isArray(raw) ? raw[0] : raw;
                    if (typeof msg === 'string') {
                        setPayoutTxidError(msg);
                    }
                },
            },
        );
    }

    function proposeApprove() {
        if (!approving) {
            return;
        }
        const trimmed = payoutTxid.trim();
        if (!trimmed) {
            setPayoutTxidError('El TXID del envío es obligatorio.');

            return;
        }
        setPayoutTxidError(null);
        setApproveSummaryOpen(true);
    }

    function openApprove(row: WithdrawalReqRow) {
        setApproving(row);
        setPayoutTxid('');
        setPayoutTxidError(null);
        setApproveSummaryOpen(false);
    }

    function confirmReject() {
        if (!rejecting) return;
        setBusyId(rejecting.id);
        router.patch(
            `/admin/retiros/solicitudes/${rejecting.id}/rechazar`,
            { admin_note: rejectNote || undefined },
            {
                preserveScroll: true,
                onFinish: () => {
                    setBusyId(null);
                    setRejecting(null);
                    setRejectNote('');
                    setRejectSummaryOpen(false);
                },
            },
        );
    }

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

            <div className="mx-auto max-w-6xl space-y-8">
                <div>
                    <Button asChild variant="ghost" size="sm" className="-ml-2 mb-2">
                        <Link href="/admin/inversion">
                            <ArrowLeft className="size-4" />
                            Administración
                        </Link>
                    </Button>
                    <h1 className="text-3xl font-bold tracking-tight">Retiros</h1>
                    <p className="mt-2 text-muted-foreground">
                        Gestiona solicitudes de los inversionistas y consulta retiros ya registrados en el libro.
                    </p>
                </div>

                <nav
                    aria-label="Secciones de retiros"
                    className="flex gap-2 overflow-x-auto border-b pb-px"
                >
                    {TABS.map((t) => (
                        <button
                            key={t.id}
                            type="button"
                            onClick={() => navigate(t.id)}
                            className={cn(
                                'inline-flex shrink-0 items-center gap-2 border-b-2 px-4 py-2.5 text-sm font-medium transition-colors',
                                tab === t.id
                                    ? 'border-primary text-foreground'
                                    : 'border-transparent text-muted-foreground hover:text-foreground',
                            )}
                        >
                            {t.label}
                            <Badge
                                className="tabular-nums"
                                variant={tab === t.id ? 'default' : 'secondary'}
                            >
                                {t.id === 'solicitudes' ? pending.length : history_rows.length}
                            </Badge>
                        </button>
                    ))}
                </nav>

                {tab === 'solicitudes' ? (
                    <>
                <Card className="border-primary/35">
                    <CardHeader>
                        <div className="flex items-center gap-2">
                            <ClipboardList className="size-5 text-primary" />
                            <CardTitle>Pendientes</CardTitle>
                        </div>
                        <CardDescription>
                            Una solicitud activa por usuario hasta que apruebas o rechazas.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="overflow-x-auto p-0">
                        {pending.length === 0 ? (
                            <p className="p-10 text-center text-sm text-muted-foreground">
                                No hay solicitudes pendientes en este momento.
                            </p>
                        ) : (
                            <table className="w-full min-w-[940px] 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="hidden px-4 py-3 font-medium xl:table-cell max-w-[200px]">
                                            Destino
                                        </th>
                                        <th className="px-4 py-3 font-medium tabular-nums">
                                            Solicitado
                                        </th>
                                        <th className="hidden px-4 py-3 font-medium tabular-nums lg:table-cell">
                                            Saldo retirable (ref.)
                                        </th>
                                        <th className="px-4 py-3 font-medium text-right">
                                            Acción
                                        </th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y">
                                    {pending.map((row) => (
                                        <tr key={row.id}>
                                            <td className="px-4 py-3">
                                                <div className="font-medium">{row.investor_name}</div>
                                                <div className="text-xs text-muted-foreground">
                                                    {row.investor_email}
                                                </div>
                                                {row.requester_note ? (
                                                    <p
                                                        className="mt-1 max-w-[220px] line-clamp-2 text-[11px] italic text-muted-foreground"
                                                        title={row.requester_note}
                                                    >
                                                        “{row.requester_note}”
                                                    </p>
                                                ) : null}
                                            </td>
                                            <td className="hidden px-4 py-3 text-xs xl:table-cell align-top max-w-[200px]">
                                                <div>{row.destination_network ?? '—'}</div>
                                                {row.destination_label ? (
                                                    <div className="text-muted-foreground">
                                                        {row.destination_label}
                                                    </div>
                                                ) : null}
                                                <div
                                                    className="break-all font-mono text-[11px]"
                                                    title={row.destination_address ?? ''}
                                                >
                                                    {row.destination_address ?? '—'}
                                                </div>
                                            </td>
                                            <td className="px-4 py-3 tabular-nums font-semibold text-primary">
                                                {row.amount_usd}
                                            </td>
                                            <td className="hidden px-4 py-3 tabular-nums lg:table-cell">
                                                {row.capital_at_request_usd ?? '—'}
                                            </td>
                                            <td className="px-4 py-3 text-right">
                                                <div className="flex flex-wrap justify-end gap-2">
                                                    <Button
                                                        disabled={busyId === row.id}
                                                        onClick={() => openApprove(row)}
                                                        size="sm"
                                                        type="button"
                                                        variant="secondary"
                                                    >
                                                        <Check className="size-4" />
                                                        Aprobar
                                                    </Button>
                                                    <Button
                                                        disabled={busyId === row.id}
                                                        onClick={() => {
                                                            setRejecting(row);
                                                            setRejectNote('');
                                                        }}
                                                        size="sm"
                                                        type="button"
                                                        variant="outline"
                                                    >
                                                        <XCircle className="size-4" />
                                                        Rechazar
                                                    </Button>
                                                </div>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        )}
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader>
                        <CardTitle>Últimas resoluciones</CardTitle>
                        <CardDescription>
                            Solicitudes ya aprobadas o rechazadas (más recientes primero).
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="overflow-x-auto p-0">
                        {recent.length === 0 ? (
                            <p className="p-8 text-center text-sm text-muted-foreground">
                                No hay registros previos visibles aquí.
                            </p>
                        ) : (
                            <table className="w-full min-w-[860px] text-left text-sm">
                                <thead>
                                    <tr className="border-b bg-muted/40 text-muted-foreground">
                                        <th className="px-4 py-3 font-medium">Estado</th>
                                        <th className="px-4 py-3 font-medium">Inversionista</th>
                                        <th className="px-4 py-3 font-medium">Origen</th>
                                        <th className="px-4 py-3 font-medium max-w-[200px]">Destino ref.</th>
                                        <th className="px-4 py-3 font-medium tabular-nums">
                                            Monto
                                        </th>
                                        <th className="px-4 py-3 font-medium">TX envío registrado</th>
                                        <th className="px-4 py-3 font-medium">Procesado</th>
                                        <th className="px-4 py-3 font-medium">Por</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y">
                                    {recent.map((row) => (
                                        <tr key={`${row.id}-recent`}>
                                            <td className="px-4 py-3">
                                                <Badge
                                                    variant={
                                                        row.status === 'approved'
                                                            ? 'secondary'
                                                            : 'outline'
                                                    }
                                                >
                                                    {row.status === 'approved'
                                                        ? 'Aprobada'
                                                        : 'Rechazada'}
                                                </Badge>
                                            </td>
                                            <td className="px-4 py-3">
                                                <div className="font-medium">{row.investor_name}</div>
                                                <div className="text-xs text-muted-foreground">
                                                    {row.investor_email}
                                                </div>
                                                {row.requester_note ? (
                                                    <p
                                                        className="mt-1 max-w-[220px] line-clamp-2 text-[11px] italic text-muted-foreground"
                                                        title={row.requester_note}
                                                    >
                                                        “{row.requester_note}”
                                                    </p>
                                                ) : null}
                                            </td>
                                            <td className="px-4 py-3 font-mono text-xs">{row.txid}</td>
                                            <td className="px-4 py-3 text-xs align-top">
                                                <div>{row.destination_network ?? '—'}</div>
                                                <div className="max-w-[180px] break-all font-mono text-[11px] text-muted-foreground" title={row.destination_address ?? ''}>
                                                    {row.destination_address ?? '—'}
                                                </div>
                                            </td>
                                            <td className="px-4 py-3 tabular-nums">{row.amount_usd}</td>
                                            <td className="px-4 py-3 font-mono text-[11px] max-w-[200px] break-all align-top">
                                                {row.status === 'approved'
                                                    ? row.payout_txid ?? (
                                                          <span className="font-sans text-muted-foreground">
                                                              —
                                                          </span>
                                                      )
                                                    : (
                                                          <span className="font-sans text-muted-foreground">
                                                              —
                                                          </span>
                                                      )}
                                            </td>
                                            <td className="px-4 py-3 text-xs text-muted-foreground whitespace-nowrap">
                                                {row.processed_at
                                                    ? new Date(row.processed_at).toLocaleString('es', {
                                                          dateStyle: 'short',
                                                          timeStyle: 'short',
                                                      })
                                                    : '—'}
                                            </td>
                                            <td className="px-4 py-3 text-sm">
                                                {row.processed_by_label}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        )}
                    </CardContent>
                </Card>
                    </>
                ) : (
                <Card>
                    <CardHeader>
                        <CardTitle>Ejecutados en el ledger</CardTitle>
                        <CardDescription>
                            Retiros directos desde administración y los tramitados vía solicitud del inversor.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="overflow-x-auto p-0">
                        {history_rows.length === 0 ? (
                            <p className="p-10 text-center text-sm text-muted-foreground">
                                Aún no hay retiros ejecutados registrados en el libro.
                            </p>
                        ) : (
                            <table className="w-full min-w-[820px] text-left text-sm">
                                <thead>
                                    <tr className="border-b bg-muted/40 text-muted-foreground">
                                        <th className="px-4 py-3 font-medium">Fecha</th>
                                        <th className="px-4 py-3 font-medium">Origen solicitud</th>
                                        <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">Monto US$</th>
                                        <th className="px-4 py-3 font-medium tabular-nums">
                                            Capital tras mov.
                                        </th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y">
                                    {history_rows.map((row) => (
                                        <tr key={row.id}>
                                            <td className="whitespace-nowrap px-4 py-3 text-xs text-muted-foreground">
                                                {row.created_at
                                                    ? new Date(row.created_at).toLocaleString('es', {
                                                          dateStyle: 'short',
                                                          timeStyle: 'short',
                                                      })
                                                    : '—'}
                                            </td>
                                            <td className="px-4 py-3">
                                                {row.via_request_id ? (
                                                    <Badge className="text-xs" variant="outline">
                                                        Solicitud #{row.via_request_id}
                                                        {row.via_request_status
                                                            ? ` · ${row.via_request_status}`
                                                            : ''}
                                                    </Badge>
                                                ) : (
                                                    <Badge className="text-xs" variant="secondary">
                                                        Manual
                                                    </Badge>
                                                )}
                                            </td>
                                            <td className="px-4 py-3">
                                                <div className="font-medium">{row.investor_name}</div>
                                                <div className="text-xs text-muted-foreground">
                                                    {row.investor_email}
                                                </div>
                                            </td>
                                            <td className="px-4 py-3 font-mono text-xs">{row.txid}</td>
                                            <td className="px-4 py-3 tabular-nums font-medium text-primary">
                                                {row.amount_usd}
                                            </td>
                                            <td className="px-4 py-3 tabular-nums">
                                                {row.balance_after_usd}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        )}
                    </CardContent>
                </Card>
                )}

                <Dialog open={rejecting !== null} onOpenChange={(open) => !open && setRejecting(null)}>
                    <DialogContent>
                        <DialogHeader>
                            <DialogTitle>Rechazar solicitud</DialogTitle>
                            <DialogDescription>
                                Opcional: deja una nota interna visible en el expediente para el equipo.
                                Inversión TXID{' '}
                                <span className="font-mono text-foreground">{rejecting?.txid}</span>.
                            </DialogDescription>
                        </DialogHeader>
                        <div className="grid gap-2 py-2">
                            <Label htmlFor="admin_note">Nota (opcional)</Label>
                            <Textarea
                                id="admin_note"
                                onChange={(e) => setRejectNote(e.target.value)}
                                placeholder="Motivo visible para otros administradores..."
                                rows={3}
                                value={rejectNote}
                            />
                        </div>
                        <DialogFooter>
                            <Button onClick={() => setRejecting(null)} type="button" variant="ghost">
                                Cancelar
                            </Button>
                            <Button
                                disabled={busyId !== null || rejecting === null}
                                onClick={() => setRejectSummaryOpen(true)}
                                type="button"
                                variant="destructive"
                            >
                                Confirmar rechazo
                            </Button>
                        </DialogFooter>
                    </DialogContent>
                </Dialog>

                <Dialog
                    open={approving !== null}
                    onOpenChange={(open) => {
                        if (!open) {
                            setApproving(null);
                            setPayoutTxid('');
                            setPayoutTxidError(null);
                            setApproveSummaryOpen(false);
                        }
                    }}
                >
                    <DialogContent>
                        <DialogHeader>
                            <DialogTitle>Aprobar retiro registrando el envío</DialogTitle>
                            <DialogDescription>
                                Este TXID quedará asociado al retiro aprobado. Monto solicitado{' '}
                                <span className="font-semibold tabular-nums">{approving?.amount_usd}</span> USD ·
                                Red o moneda declarada{' '}
                                <span className="font-medium">{approving?.destination_network ?? '—'}</span>.
                            </DialogDescription>
                        </DialogHeader>
                        <div className="grid gap-2 py-2">
                            <Label htmlFor="payout_txid">
                                TXID del envío real (BTC / USDT / otra cadena según proceso)
                            </Label>
                            <Input
                                id="payout_txid"
                                className="font-mono text-xs"
                                onChange={(e) => setPayoutTxid(e.target.value)}
                                placeholder="Identificador del envío en la cadena correspondiente..."
                                value={payoutTxid}
                            />
                            {payoutTxidError ? (
                                <p className="text-sm text-destructive">{payoutTxidError}</p>
                            ) : null}
                            {approving?.destination_address ? (
                                <div className="rounded-md bg-muted/50 p-2 text-[11px] font-mono break-all">
                                    <span className="text-muted-foreground">Dirección destino usuario: </span>
                                    {approving.destination_address}
                                </div>
                            ) : null}
                            {approving?.requester_note ? (
                                <div className="rounded-md border border-dashed px-3 py-2 text-sm">
                                    <p className="text-[11px] font-medium uppercase text-muted-foreground">
                                        Comentario del inversionista
                                    </p>
                                    <p className="mt-1 whitespace-pre-wrap text-sm">{approving.requester_note}</p>
                                </div>
                            ) : null}
                        </div>
                        <DialogFooter>
                            <Button
                                onClick={() => {
                                    setApproving(null);
                                    setPayoutTxid('');
                                    setPayoutTxidError(null);
                                }}
                                type="button"
                                variant="ghost"
                            >
                                Cancelar
                            </Button>
                            <Button disabled={busyId !== null || approving === null} onClick={proposeApprove} type="button">
                                Continuar
                            </Button>
                        </DialogFooter>
                    </DialogContent>
                </Dialog>
            </div>

            <ConfirmActionModal
                cancelLabel="Volver"
                confirmLabel="Sí, aprobar retiro"
                confirmVariant="default"
                description="Se descontará el saldo retirable del balance general del usuario y quedará registrado el TXID de envío."
                open={approveSummaryOpen}
                processing={busyId !== null && approving !== null && busyId === approving.id}
                title="¿Aprobar este retiro?"
                onConfirm={confirmApprove}
                onOpenChange={(open) => !open && setApproveSummaryOpen(false)}
            >
                {approving ? (
                    <div className="space-y-2 text-muted-foreground">
                        <p>
                            <span className="font-medium text-foreground">Inversionista:</span> {approving.investor_name}
                        </p>
                        <p>
                            <span className="font-medium text-foreground">Monto solicitado:</span>{' '}
                            <span className="tabular-nums text-foreground">{approving.amount_usd} US$</span>
                        </p>
                        <p className="font-mono text-xs break-all">
                            <span className="font-sans font-medium text-foreground">TXID payout:</span> {payoutTxid.trim()}
                        </p>
                    </div>
                ) : null}
            </ConfirmActionModal>

            <ConfirmActionModal
                cancelLabel="Volver"
                confirmLabel="Sí, rechazar"
                confirmVariant="destructive"
                description="El balance retirable del usuario no se modifica. Puedes dejar una nota interna en el expediente."
                open={rejectSummaryOpen}
                processing={busyId !== null && rejecting !== null && busyId === rejecting.id}
                title="¿Rechazar esta solicitud de retiro?"
                onConfirm={confirmReject}
                onOpenChange={(open) => !open && setRejectSummaryOpen(false)}
            >
                {rejecting ? (
                    <div className="space-y-2 text-muted-foreground">
                        <p>
                            <span className="font-medium text-foreground">Inversionista:</span> {rejecting.investor_name}
                        </p>
                        <p>
                            <span className="font-medium text-foreground">Monto:</span>{' '}
                            <span className="tabular-nums text-foreground">{rejecting.amount_usd} US$</span>
                        </p>
                        {rejectNote.trim() ? (
                            <p className="border-t pt-2 text-xs">
                                <span className="font-medium text-foreground">Nota:</span> {rejectNote.trim()}
                            </p>
                        ) : null}
                    </div>
                ) : null}
            </ConfirmActionModal>
        </>
    );
}

WithdrawalRequests.layout = {
    breadcrumbs: [
        { title: 'Administración', href: '/admin' },
        { title: 'Retiros', href: '/admin/retiros/solicitudes' },
    ],
};
