import { Head, Link, router } from '@inertiajs/react';
import {
    Ban,
    CheckCircle2,
    CircleCheck,
    ClipboardList,
    Eye,
    Loader2,
    MoreHorizontal,
    Percent,
    RotateCcw,
    Search,
    UserPlus,
    type LucideIcon,
} from 'lucide-react';
import { type FormEvent, type ReactNode, useState } from 'react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
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 {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { InertiaPaginatorFooter, type InertiaPaginatorSlice } from '@/components/inertia-paginator-footer';
import { cn } from '@/lib/utils';

type UserLite = {
    id: number;
    first_name: string;
    last_name: string;
    email: string;
    name?: string;
};

export type PendingInvestmentAdmin = {
    id: number;
    user_id: number;
    amount: string;
    duration_months: number;
    monthly_return_snapshot: string;
    txid: string;
    created_at: string;
    user: UserLite | null;
};

export type ActiveInvestmentAdmin = PendingInvestmentAdmin & {
    confirmed_at: string | null;
    capital_balance: string | null;
    months_credited: number;
    status: string;
};

export type CancelledInvestmentAdmin = ActiveInvestmentAdmin;

type TabId = 'active' | 'pending' | 'completed' | 'cancelled';

type Filters = {
    q: string;
    tab: TabId;
};

type PendingReferralRow = {
    level: number;
    level_label: string;
    beneficiary_user_id: number;
    beneficiary_name: string;
    beneficiary_email: string | null;
    percent: string;
    target_amount_usd: string;
    already_paid_usd: string;
    pending_amount_usd: string;
};

type PendingReferralsPayload = {
    investment: {
        id: number;
        txid: string;
        amount_usd: string;
        investor_name: string;
        investor_email: string | null;
    };
    pending: PendingReferralRow[];
};

type PaginatedInvestments = InertiaPaginatorSlice & {
    data: Array<PendingInvestmentAdmin | ActiveInvestmentAdmin>;
};

type Props = {
    investments: PaginatedInvestments;
    tab_counts: Record<TabId, number>;
    summary: {
        active_count: number;
        total_capital_usd: string;
    };
    filters: Filters;
    adjustments_enabled?: boolean;
};

const TABS: { id: TabId; label: string }[] = [
    { id: 'active', label: 'Activas' },
    { id: 'pending', label: 'Por confirmar' },
    { id: 'completed', label: 'Finalizadas' },
    { id: 'cancelled', label: 'Anuladas' },
];

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

function formatDateShort(iso: string): string {
    return new Date(iso).toLocaleString('es', {
        dateStyle: 'short',
        timeStyle: 'short',
    });
}

function investorLabel(user: UserLite | null | undefined): string {
    return (
        (user?.name ??
            [user?.first_name, user?.last_name].filter(Boolean).join(' ').trim()) ||
        '(usuario)'
    );
}

const TH =
    'text-muted-foreground px-4 py-3 text-left text-xs font-medium whitespace-nowrap';
const TD = 'px-4 py-3 align-middle';

function InlineSearch({
    value,
    onChange,
    onSubmit,
    onClear,
    hasFilter,
    className,
}: {
    value: string;
    onChange: (value: string) => void;
    onSubmit: (event: FormEvent) => void;
    onClear: () => void;
    hasFilter: boolean;
    className?: string;
}) {
    return (
        <form
            className={cn('flex w-full items-center gap-1 sm:max-w-xs', className)}
            onSubmit={onSubmit}
        >
            <div className="relative min-w-0 flex-1">
                <Search
                    aria-hidden
                    className="text-muted-foreground pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2"
                />
                <Input
                    aria-label="Buscar inversiones"
                    className="h-9 pl-8 text-sm"
                    placeholder="Buscar…"
                    value={value}
                    onChange={(e) => onChange(e.target.value)}
                />
            </div>
            {hasFilter ? (
                <Button
                    className="shrink-0 px-2 text-xs"
                    onClick={onClear}
                    type="button"
                    variant="ghost"
                >
                    Limpiar
                </Button>
            ) : null}
        </form>
    );
}

function ListCardHeader({
    title,
    icon: Icon,
    search,
}: {
    title: string;
    icon?: LucideIcon;
    search: ReactNode;
}) {
    return (
        <CardHeader className="flex flex-col gap-3 border-b py-4 sm:flex-row sm:items-center sm:justify-between">
            <CardTitle className="flex shrink-0 items-center gap-2 text-lg">
                {Icon ? <Icon className="size-5" /> : null}
                {title}
            </CardTitle>
            {search}
        </CardHeader>
    );
}

export default function InvestmentsOverview({
    investments,
    tab_counts,
    summary,
    filters,
    adjustments_enabled = false,
}: Props) {
    const [confirmingId, setConfirmingId] = useState<number | null>(null);
    const [toConfirmRow, setToConfirmRow] = useState<PendingInvestmentAdmin | null>(null);
    const [voidingId, setVoidingId] = useState<number | null>(null);
    const [toVoidRow, setToVoidRow] = useState<
        PendingInvestmentAdmin | ActiveInvestmentAdmin | null
    >(null);
    const [reactivatingId, setReactivatingId] = useState<number | null>(null);
    const [toReactivateRow, setToReactivateRow] = useState<ActiveInvestmentAdmin | null>(null);
    const [reactivateExtensionMonths, setReactivateExtensionMonths] = useState('0');
    const [finalizingId, setFinalizingId] = useState<number | null>(null);
    const [toFinalizeRow, setToFinalizeRow] = useState<ActiveInvestmentAdmin | null>(null);
    const [referralTarget, setReferralTarget] = useState<ActiveInvestmentAdmin | null>(null);
    const [referralPreview, setReferralPreview] = useState<PendingReferralsPayload | null>(null);
    const [referralLoading, setReferralLoading] = useState(false);
    const [referralError, setReferralError] = useState<string | null>(null);
    const [referralApplying, setReferralApplying] = useState(false);
    const [selectedReferralLevels, setSelectedReferralLevels] = useState<number[]>([]);
    const [searchQuery, setSearchQuery] = useState(filters.q);
    const currentTab = filters.tab;
    const rows = investments.data;

    const tabCounts = tab_counts;

    function navigate(tab: TabId, q = searchQuery.trim(), page = 1) {
        router.get(
            '/admin/inversiones',
            { q, tab, page },
            { preserveState: true, replace: true, preserveScroll: page > 1 },
        );
    }

    function confirmInvestment(id: number) {
        setConfirmingId(id);
        router.patch(
            `/admin/inversiones/${id}/confirmar`,
            { q: filters.q, tab: filters.tab, page: investments.current_page },
            {
            onFinish: () => {
                setConfirmingId(null);
                setToConfirmRow(null);
            },
        },
        );
    }

    function submitSearch(event: FormEvent) {
        event.preventDefault();
        navigate(currentTab);
    }

    function clearSearch() {
        setSearchQuery('');
        navigate(currentTab, '');
    }

    const inlineSearch = (
        <InlineSearch
            hasFilter={filters.q.length > 0}
            value={searchQuery}
            onChange={setSearchQuery}
            onClear={clearSearch}
            onSubmit={submitSearch}
        />
    );

    function voidInvestment(id: number) {
        setVoidingId(id);
        router.patch(
            `/admin/inversiones/${id}/anular`,
            { q: filters.q, tab: filters.tab, page: investments.current_page },
            {
                onFinish: () => {
                    setVoidingId(null);
                    setToVoidRow(null);
                },
            },
        );
    }

    function reactivateInvestment(id: number) {
        setReactivatingId(id);
        router.patch(
            `/admin/inversiones/${id}/reactivar`,
            {
                q: filters.q,
                tab: filters.tab,
                page: investments.current_page,
                extension_months: Number(reactivateExtensionMonths),
            },
            {
                onFinish: () => {
                    setReactivatingId(null);
                    setToReactivateRow(null);
                    setReactivateExtensionMonths('0');
                },
            },
        );
    }

    function finalizeInvestment(id: number) {
        setFinalizingId(id);
        router.patch(
            `/admin/inversiones/${id}/finalizar`,
            { q: filters.q, tab: filters.tab, page: investments.current_page },
            {
                onFinish: () => {
                    setFinalizingId(null);
                    setToFinalizeRow(null);
                },
            },
        );
    }

    function canFinalizeInvestment(row: ActiveInvestmentAdmin): boolean {
        return (row.months_credited ?? 0) >= row.duration_months;
    }

    function closeReferralModal() {
        setReferralTarget(null);
        setReferralPreview(null);
        setReferralError(null);
        setSelectedReferralLevels([]);
    }

    async function openReferralModal(row: ActiveInvestmentAdmin) {
        setReferralTarget(row);
        setReferralPreview(null);
        setReferralError(null);
        setSelectedReferralLevels([]);
        setReferralLoading(true);

        try {
            const response = await fetch(`/admin/inversiones/${row.id}/referidos-pendientes`, {
                headers: { Accept: 'application/json' },
            });

            if (!response.ok) {
                throw new Error('No se pudo cargar el detalle de referidos.');
            }

            const payload = (await response.json()) as PendingReferralsPayload;
            setReferralPreview(payload);
            setSelectedReferralLevels(payload.pending.map((item) => item.level));
        } catch {
            setReferralError('No se pudo cargar el detalle de referidos.');
        } finally {
            setReferralLoading(false);
        }
    }

    function applyReferrals() {
        if (!referralTarget || selectedReferralLevels.length === 0) {
            return;
        }

        setReferralApplying(true);
        router.post(
            `/admin/inversiones/${referralTarget.id}/referidos`,
            {
                levels: selectedReferralLevels,
                q: filters.q,
                tab: filters.tab,
                page: investments.current_page,
            },
            {
                onFinish: () => {
                    setReferralApplying(false);
                    closeReferralModal();
                },
            },
        );
    }

    function toggleReferralLevel(level: number, checked: boolean) {
        setSelectedReferralLevels((current) =>
            checked ? [...current, level] : current.filter((value) => value !== level),
        );
    }

    function renderReferralMenuItem(row: ActiveInvestmentAdmin) {
        return (
            <DropdownMenuItem onClick={() => openReferralModal(row)}>
                <UserPlus className="size-4" />
                Recalcular referidos
            </DropdownMenuItem>
        );
    }

    function renderRowActions(
        row: ActiveInvestmentAdmin,
        mode: 'active' | 'completed' | 'readonly',
    ) {
        return (
            <div className="flex items-center justify-end gap-0.5">
                <Button asChild size="icon" variant="ghost">
                    <Link
                        href={`/admin/inversiones/${row.id}/acreditaciones`}
                        title="Ver acreditaciones"
                    >
                        <Eye className="size-4" />
                        <span className="sr-only">Acreditaciones</span>
                    </Link>
                </Button>
                {mode === 'active' ? (
                    <>
                        <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                                <Button aria-label="Más acciones" size="icon" type="button" variant="ghost">
                                    <MoreHorizontal className="size-4" />
                                </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                                {adjustments_enabled && canFinalizeInvestment(row) ? (
                                    <DropdownMenuItem onClick={() => setToFinalizeRow(row)}>
                                        <CircleCheck className="size-4" />
                                        Finalizar contrato
                                    </DropdownMenuItem>
                                ) : null}
                                <DropdownMenuItem
                                    className="text-destructive focus:text-destructive"
                                    onClick={() => requestVoid(row)}
                                >
                                    <Ban className="size-4" />
                                    Anular inversión
                                </DropdownMenuItem>
                                {renderReferralMenuItem(row)}
                            </DropdownMenuContent>
                        </DropdownMenu>
                    </>
                ) : null}
                {mode === 'completed' ? (
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button aria-label="Más acciones" size="icon" type="button" variant="ghost">
                                <MoreHorizontal className="size-4" />
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                            <DropdownMenuItem onClick={() => requestReactivate(row)}>
                                <RotateCcw className="size-4" />
                                Reactivar inversión
                            </DropdownMenuItem>
                            {renderReferralMenuItem(row)}
                        </DropdownMenuContent>
                    </DropdownMenu>
                ) : null}
            </div>
        );
    }

    function renderPaginationFooter() {
        if (investments.last_page <= 1) {
            return null;
        }

        return <InertiaPaginatorFooter paginator={investments} />;
    }

    function renderActiveTable(rows: ActiveInvestmentAdmin[], mode: 'active' | 'completed' | 'readonly') {
        if (rows.length === 0) {
            return (
                <p className="text-muted-foreground px-4 py-10 text-center text-sm">
                    {filters.q
                        ? 'Sin resultados para esta búsqueda.'
                        : 'No hay inversiones en esta categoría.'}
                </p>
            );
        }

        return (
            <>
                <div className="overflow-x-auto">
                    <table className="w-full table-fixed text-sm">
                    <colgroup>
                        <col className="w-[22%]" />
                        <col className="w-[11%]" />
                        <col className="w-[10%]" />
                        <col className="w-[11%]" />
                        <col className="w-[8%]" />
                        <col className="w-[8%]" />
                        <col className="w-[14%]" />
                        <col className="w-[16%]" />
                    </colgroup>
                    <thead className="bg-muted/30 border-b">
                        <tr>
                            <th className={TH}>Inversionista</th>
                            <th className={TH}>TXID</th>
                            <th className={cn(TH, 'text-right')}>Principal</th>
                            <th className={cn(TH, 'text-primary text-right')}>Capital</th>
                            <th className={cn(TH, 'text-center')}>Acreditaciones</th>
                            <th className={cn(TH, 'text-right')}>Plan</th>
                            <th className={TH}>Confirmada</th>
                            <th className={cn(TH, 'text-right')}>Acciones</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y">
                        {rows.map((row) => (
                            <tr key={row.id} className="hover:bg-muted/20">
                                <td className={TD}>
                                    <div className="truncate font-medium">
                                        {investorLabel(row.user)}
                                    </div>
                                    <div className="text-muted-foreground truncate text-xs">
                                        {row.user?.email}
                                    </div>
                                </td>
                                <td className={cn(TD, 'font-mono text-xs')}>
                                    <span className="line-clamp-2 break-all">{row.txid}</span>
                                </td>
                                <td className={cn(TD, 'text-right tabular-nums')}>
                                    {formatUsd(row.amount)}
                                </td>
                                <td className={cn(TD, 'text-primary text-right font-semibold tabular-nums')}>
                                    {formatUsd(row.capital_balance ?? row.amount)}
                                </td>
                                <td className={cn(TD, 'text-muted-foreground text-center tabular-nums')}>
                                    {row.months_credited ?? 0}/{row.duration_months}
                                </td>
                                <td className={cn(TD, 'text-right tabular-nums')}>
                                    {row.monthly_return_snapshot}%
                                </td>
                                <td className={cn(TD, 'text-muted-foreground text-xs whitespace-nowrap')}>
                                    {row.confirmed_at ? formatDateShort(row.confirmed_at) : '—'}
                                </td>
                                <td className={cn(TD, 'text-right')}>
                                    {renderRowActions(row, mode)}
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
                </div>
                {renderPaginationFooter()}
            </>
        );
    }

    function requestConfirm(row: PendingInvestmentAdmin) {
        setToConfirmRow(row);
    }

    function requestVoid(row: PendingInvestmentAdmin | ActiveInvestmentAdmin) {
        setToVoidRow(row);
    }

    function requestReactivate(row: ActiveInvestmentAdmin) {
        setReactivateExtensionMonths('0');
        setToReactivateRow(row);
    }

    return (
        <>
            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, confirmar inversión"
                confirmVariant="default"
                description="Esto activará la inversión y registrará el depósito en el libro, tras haber verificado el pago en cadena."
                open={toConfirmRow !== null}
                processing={
                    toConfirmRow !== null &&
                    confirmingId !== null &&
                    confirmingId === toConfirmRow.id
                }
                title="¿Confirmar esta inversión como activa?"
                onConfirm={() => {
                    if (toConfirmRow) {
                        confirmInvestment(toConfirmRow.id);
                    }
                }}
                onOpenChange={(open) => !open && setToConfirmRow(null)}
            >
                {toConfirmRow ? (
                    <div className="text-muted-foreground space-y-2">
                        <p>
                            <span className="text-foreground font-medium">Monto:</span> USD{' '}
                            {formatUsd(toConfirmRow.amount)}
                        </p>
                        <p className="font-mono text-xs break-all">TXID: {toConfirmRow.txid}</p>
                    </div>
                ) : null}
            </ConfirmActionModal>

            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, reactivar inversión"
                confirmVariant="default"
                description="La inversión volverá al estado activo. Puedes reactivarla sin prórroga o extender el contrato del usuario entre 1 y 12 meses."
                open={toReactivateRow !== null}
                processing={
                    toReactivateRow !== null &&
                    reactivatingId !== null &&
                    reactivatingId === toReactivateRow.id
                }
                title="¿Reactivar esta inversión finalizada?"
                onConfirm={() => {
                    if (toReactivateRow) {
                        reactivateInvestment(toReactivateRow.id);
                    }
                }}
                onOpenChange={(open) => {
                    if (!open) {
                        setToReactivateRow(null);
                        setReactivateExtensionMonths('0');
                    }
                }}
            >
                {toReactivateRow ? (
                    <div className="text-muted-foreground space-y-2">
                        <p>
                            <span className="text-foreground font-medium">Inversionista:</span>{' '}
                            {investorLabel(toReactivateRow.user)}
                        </p>
                        <p>
                            <span className="text-foreground font-medium">Capital:</span> USD{' '}
                            {formatUsd(toReactivateRow.capital_balance ?? toReactivateRow.amount)}
                        </p>
                        <div className="space-y-2 pt-2">
                            <Label htmlFor="reactivate-extension-months">Prórroga del contrato</Label>
                            <Select
                                value={reactivateExtensionMonths}
                                onValueChange={setReactivateExtensionMonths}
                            >
                                <SelectTrigger id="reactivate-extension-months" className="w-full">
                                    <SelectValue />
                                </SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="0">Ninguno, solo reactivar</SelectItem>
                                    {Array.from({ length: 12 }, (_, index) => index + 1).map((months) => (
                                        <SelectItem key={months} value={String(months)}>
                                            {months} {months === 1 ? 'mes' : 'meses'}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                            <p className="text-xs leading-relaxed">
                                Si eliges meses adicionales, se sumarán al plazo y al vencimiento actual de la inversión.
                            </p>
                        </div>
                        <p className="font-mono text-xs break-all">TXID: {toReactivateRow.txid}</p>
                    </div>
                ) : null}
            </ConfirmActionModal>

            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, finalizar contrato"
                confirmVariant="default"
                description="Marca la inversión como finalizada. Solo disponible cuando ya se acreditaron todos los meses del plan."
                open={toFinalizeRow !== null}
                processing={
                    toFinalizeRow !== null &&
                    finalizingId !== null &&
                    finalizingId === toFinalizeRow.id
                }
                title="¿Finalizar esta inversión?"
                onConfirm={() => {
                    if (toFinalizeRow) {
                        finalizeInvestment(toFinalizeRow.id);
                    }
                }}
                onOpenChange={(open) => !open && setToFinalizeRow(null)}
            >
                {toFinalizeRow ? (
                    <div className="text-muted-foreground space-y-2">
                        <p>
                            <span className="text-foreground font-medium">Acreditaciones:</span>{' '}
                            {toFinalizeRow.months_credited ?? 0} / {toFinalizeRow.duration_months}
                        </p>
                        <p>
                            <span className="text-foreground font-medium">Capital:</span> USD{' '}
                            {formatUsd(toFinalizeRow.capital_balance ?? toFinalizeRow.amount)}
                        </p>
                        <p className="font-mono text-xs break-all">TXID: {toFinalizeRow.txid}</p>
                    </div>
                ) : null}
            </ConfirmActionModal>

            <Dialog open={referralTarget !== null} onOpenChange={(open) => !open && closeReferralModal()}>
                <DialogContent className="sm:max-w-lg">
                    <DialogHeader>
                        <DialogTitle>Recalcular referidos</DialogTitle>
                        <DialogDescription className="text-left">
                            Comisiones de referido sobre el capital pactado que aún no se acreditaron
                            en esta inversión.
                        </DialogDescription>
                    </DialogHeader>

                    {referralTarget ? (
                        <div className="text-muted-foreground space-y-1 text-sm">
                            <p>
                                <span className="text-foreground font-medium">Inversión:</span>{' '}
                                {referralTarget.txid.substring(0, 8)}...
                            </p>
                            <p>
                                <span className="text-foreground font-medium">Capital:</span> USD{' '}
                                {formatUsd(referralTarget.amount)}
                            </p>
                        </div>
                    ) : null}

                    <div className="max-h-[40vh] overflow-y-auto text-sm">
                        {referralLoading ? (
                            <p className="text-muted-foreground flex items-center gap-2 py-4">
                                <Loader2 className="size-4 animate-spin" />
                                Cargando referidos pendientes…
                            </p>
                        ) : null}

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

                        {!referralLoading && !referralError && referralPreview?.pending.length === 0 ? (
                            <p className="text-muted-foreground py-4">
                                No hay comisiones de referido pendientes para esta inversión.
                            </p>
                        ) : null}

                        {!referralLoading && !referralError && referralPreview && referralPreview.pending.length > 0 ? (
                            <ul className="space-y-3">
                                {referralPreview.pending.map((item) => (
                                    <li
                                        key={item.level}
                                        className="border-border flex gap-3 rounded-lg border p-3"
                                    >
                                        <Checkbox
                                            checked={selectedReferralLevels.includes(item.level)}
                                            id={`referral-level-${item.level}`}
                                            onCheckedChange={(checked) =>
                                                toggleReferralLevel(item.level, checked === true)
                                            }
                                        />
                                        <label
                                            className="min-w-0 flex-1 cursor-pointer space-y-1"
                                            htmlFor={`referral-level-${item.level}`}
                                        >
                                            <p className="text-foreground font-medium">
                                                {item.level_label} · {item.beneficiary_name}
                                            </p>
                                            {item.beneficiary_email ? (
                                                <p className="text-muted-foreground text-xs">
                                                    {item.beneficiary_email}
                                                </p>
                                            ) : null}
                                            <p>
                                                Objetivo: USD {formatUsd(item.target_amount_usd)} (
                                                {item.percent}%)
                                            </p>
                                            <p>
                                                Ya acreditado: USD {formatUsd(item.already_paid_usd)}
                                            </p>
                                            <p className="text-foreground font-medium">
                                                Pendiente: USD {formatUsd(item.pending_amount_usd)}
                                            </p>
                                        </label>
                                    </li>
                                ))}
                            </ul>
                        ) : null}
                    </div>

                    <DialogFooter className="gap-2 sm:gap-0">
                        <Button
                            disabled={referralApplying}
                            onClick={closeReferralModal}
                            type="button"
                            variant="ghost"
                        >
                            Cancelar
                        </Button>
                        <Button
                            disabled={
                                referralApplying
                                || referralLoading
                                || selectedReferralLevels.length === 0
                                || !referralPreview?.pending.length
                            }
                            onClick={applyReferrals}
                            type="button"
                        >
                            {referralApplying ? 'Acreditando…' : 'Acreditar seleccionados'}
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>

            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, anular inversión"
                confirmVariant="destructive"
                description="Esta acción es irreversible."
                open={toVoidRow !== null}
                processing={
                    toVoidRow !== null && voidingId !== null && voidingId === toVoidRow.id
                }
                title="¿Anular esta inversión?"
                onConfirm={() => {
                    if (toVoidRow) {
                        voidInvestment(toVoidRow.id);
                    }
                }}
                onOpenChange={(open) => !open && setToVoidRow(null)}
            />

            <Head title="Inversiones y balances" />

            <div className="space-y-8">
                <div>
                    <h1 className="text-3xl font-bold tracking-tight">
                        Inversiones y balances
                    </h1>
                    <p className="text-muted-foreground">
                        Gestión de solicitudes, capital vigente y detalle de acreditaciones por
                        contrato.
                    </p>
                </div>

                <nav
                    aria-label="Estado de inversiones"
                    className="flex gap-2 overflow-x-auto border-b pb-px"
                >
                    {TABS.map((tab) => (
                        <button
                            key={tab.id}
                            type="button"
                            onClick={() => navigate(tab.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',
                                currentTab === tab.id
                                    ? 'border-primary text-foreground'
                                    : 'text-muted-foreground hover:text-foreground border-transparent',
                            )}
                        >
                            {tab.label}
                            <Badge
                                className="tabular-nums"
                                variant={currentTab === tab.id ? 'default' : 'secondary'}
                            >
                                {tabCounts[tab.id]}
                            </Badge>
                        </button>
                    ))}
                </nav>

                {currentTab === 'active' && (
                    <div className="space-y-6">
                        <div className="grid gap-4 sm:grid-cols-2">
                            <Card>
                                <CardHeader className="pb-2">
                                    <CardDescription>Inversiones activas</CardDescription>
                                    <CardTitle className="text-3xl tabular-nums">
                                        {summary.active_count}
                                    </CardTitle>
                                </CardHeader>
                            </Card>
                            <Card className="border-primary/35 bg-primary/10">
                                <CardHeader className="pb-2">
                                    <CardDescription>Capital total vigente (US$)</CardDescription>
                                    <CardTitle className="text-primary text-3xl tabular-nums">
                                        {summary.total_capital_usd}
                                    </CardTitle>
                                </CardHeader>
                            </Card>
                        </div>

                        <Card>
                            <ListCardHeader
                                icon={ClipboardList}
                                search={inlineSearch}
                                title="Inversiones activas"
                            />
                            <CardContent className="p-0">
                                {renderActiveTable(rows as ActiveInvestmentAdmin[], 'active')}
                            </CardContent>
                        </Card>
                    </div>
                )}

                {currentTab === 'pending' && (
                    <Card>
                        <ListCardHeader search={inlineSearch} title="Por confirmar" />
                        <CardContent className="space-y-0 p-0">
                            {rows.length === 0 ? (
                                <p className="text-muted-foreground px-4 py-8 text-center text-sm">
                                    {filters.q
                                        ? 'Sin resultados para esta búsqueda.'
                                        : 'No hay solicitudes pendientes.'}
                                </p>
                            ) : (
                                <>
                                    <ul className="divide-y">
                                        {(rows as PendingInvestmentAdmin[]).map((row) => (
                                        <li
                                            key={row.id}
                                            className="flex flex-col gap-3 px-4 py-4 md:flex-row md:items-start md:justify-between"
                                        >
                                            <div className="min-w-0 space-y-2">
                                                <div className="flex flex-wrap items-center gap-2">
                                                    <Badge variant="outline">Pendiente</Badge>
                                                    <span className="font-semibold tabular-nums">
                                                        USD {formatUsd(row.amount)}
                                                    </span>
                                                    <span className="text-muted-foreground text-sm">
                                                        {row.duration_months} meses
                                                    </span>
                                                </div>
                                                <p className="text-sm">
                                                    {investorLabel(row.user)} · {row.user?.email}
                                                </p>
                                                <p className="text-muted-foreground font-mono text-xs break-all">
                                                    TXID: {row.txid}
                                                </p>
                                            </div>
                                            <div className="flex shrink-0 gap-2">
                                                <Button
                                                    disabled={confirmingId === row.id}
                                                    onClick={() => requestConfirm(row)}
                                                    size="sm"
                                                    type="button"
                                                >
                                                    {confirmingId === row.id ? (
                                                        <Loader2 className="size-4 animate-spin" />
                                                    ) : (
                                                        <CheckCircle2 className="size-4" />
                                                    )}
                                                    Confirmar
                                                </Button>
                                                <Button
                                                    onClick={() => requestVoid(row)}
                                                    size="sm"
                                                    type="button"
                                                    variant="outline"
                                                >
                                                    <Ban className="size-4" />
                                                    Anular
                                                </Button>
                                            </div>
                                        </li>
                                    ))}
                                    </ul>
                                    {renderPaginationFooter()}
                                </>
                            )}
                        </CardContent>
                    </Card>
                )}

                {currentTab === 'completed' && (
                    <Card>
                        <ListCardHeader search={inlineSearch} title="Finalizadas" />
                        <CardContent className="p-0">
                            {renderActiveTable(rows as ActiveInvestmentAdmin[], 'completed')}
                        </CardContent>
                    </Card>
                )}

                {currentTab === 'cancelled' && (
                    <Card>
                        <ListCardHeader search={inlineSearch} title="Anuladas" />
                        <CardContent className="p-0">
                            {rows.length === 0 ? (
                                <p className="text-muted-foreground px-4 py-10 text-center text-sm">
                                    {filters.q
                                        ? 'Sin resultados para esta búsqueda.'
                                        : 'No hay inversiones anuladas.'}
                                </p>
                            ) : (
                                <>
                                <div className="overflow-x-auto">
                                    <table className="w-full table-fixed text-sm">
                                        <colgroup>
                                            <col className="w-[32%]" />
                                            <col className="w-[28%]" />
                                            <col className="w-[18%]" />
                                            <col className="w-[22%]" />
                                        </colgroup>
                                        <thead className="bg-muted/30 border-b">
                                            <tr>
                                                <th className={TH}>Inversionista</th>
                                                <th className={TH}>TXID</th>
                                                <th className={cn(TH, 'text-right')}>Principal</th>
                                                <th className={TH}>Registro</th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y">
                                            {(rows as CancelledInvestmentAdmin[]).map((row) => (
                                                <tr key={row.id} className="hover:bg-muted/20">
                                                    <td className={TD}>
                                                        <div className="truncate font-medium">
                                                            {investorLabel(row.user)}
                                                        </div>
                                                        <div className="text-muted-foreground truncate text-xs">
                                                            {row.user?.email}
                                                        </div>
                                                    </td>
                                                    <td className={cn(TD, 'font-mono text-xs')}>
                                                        <span className="line-clamp-2 break-all">
                                                            {row.txid}
                                                        </span>
                                                    </td>
                                                    <td className={cn(TD, 'text-right tabular-nums')}>
                                                        {formatUsd(row.amount)}
                                                    </td>
                                                    <td className={cn(TD, 'text-muted-foreground text-xs whitespace-nowrap')}>
                                                        {formatDateShort(row.created_at)}
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                                {renderPaginationFooter()}
                                </>
                            )}
                        </CardContent>
                    </Card>
                )}
            </div>
        </>
    );
}

InvestmentsOverview.layout = {
    breadcrumbs: [
        { title: 'Administración', href: '/admin' },
        { title: 'Inversiones', href: '/admin/inversiones' },
    ],
};
