import { Head, Link, router, useForm, usePage } from '@inertiajs/react';
import {
    ArrowDownToLine,
    ArrowLeft,
    Eye,
    Layers,
    Search,
    Share2,
    Shield,
    Sparkles,
    User,
    Undo2,
    UserSearch,
    Users,
    Wallet,
    type LucideIcon,
} from 'lucide-react';
import type { FormEvent, ReactNode } from 'react';
import { useEffect, useMemo, useState } from 'react';
import Heading from '@/components/heading';
import { ConfirmActionModal } from '@/components/confirm-action-modal';
import InputError from '@/components/input-error';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { countryOptions } from '@/lib/countries';
import { cn } from '@/lib/utils';
import type { User as AuthUser } from '@/types/auth';

type SectionId =
    | 'perfil'
    | 'jabes_women'
    | 'programa_referidos'
    | 'referidor'
    | 'referidos_directos'
    | 'acceso'
    | 'balance';

function SettingsSection({
    title,
    description,
    icon: Icon,
    children,
}: {
    title: string;
    description: string;
    icon: LucideIcon;
    children: ReactNode;
}) {
    return (
        <Card className="border-border/80 shadow-sm">
            <CardHeader className="border-b border-border/60 bg-muted/20 pb-4">
                <div className="flex gap-3">
                    <div className="bg-primary/10 text-primary flex size-10 shrink-0 items-center justify-center rounded-lg">
                        <Icon className="size-5" aria-hidden />
                    </div>
                    <div className="min-w-0 space-y-1">
                        <CardTitle className="text-base">{title}</CardTitle>
                        <CardDescription className="text-sm leading-relaxed">
                            {description}
                        </CardDescription>
                    </div>
                </div>
            </CardHeader>
            <CardContent className="space-y-6 pt-6">{children}</CardContent>
        </Card>
    );
}

function ToggleRow({
    id,
    checked,
    onCheckedChange,
    title,
    description,
    destructive,
    disabled,
}: {
    id: string;
    checked: boolean;
    onCheckedChange: (value: boolean) => void;
    title: string;
    description: string;
    destructive?: boolean;
    disabled?: boolean;
}) {
    return (
        <div className="flex items-start gap-3 rounded-lg border border-border/80 bg-background/50 p-4">
            <Checkbox
                checked={checked}
                disabled={disabled}
                id={id}
                onCheckedChange={(v) => onCheckedChange(v === true)}
                className="mt-0.5"
            />
            <div className="grid min-w-0 flex-1 gap-1">
                <Label
                    className={cn(
                        'cursor-pointer font-medium leading-snug',
                        destructive && 'text-destructive',
                    )}
                    htmlFor={id}
                >
                    {title}
                </Label>
                <p className="text-muted-foreground text-sm leading-relaxed">{description}</p>
            </div>
        </div>
    );
}

type ReferrerRow = {
    id: number;
    name: string;
    email: string;
    referral_code: string;
    referral_program_enabled: boolean;
};

function firstError(value: string | string[] | undefined): string | undefined {
    if (value === undefined || value === '') {
        return undefined;
    }

    return Array.isArray(value) ? value[0] : value;
}

function formatUsdDisplay(value: string | number): string {
    const n = typeof value === 'string' ? Number.parseFloat(value) : value;

    if (!Number.isFinite(n)) {
        return '0.00';
    }

    return new Intl.NumberFormat('es-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
    }).format(n);
}

type ManualBalanceCredit = {
    id: number;
    amount_usd: string;
    balance_after_usd: string;
    admin_note: string | null;
    created_at: string | null;
    created_by: { id: number; name: string; email: string } | null;
    reversed_at: string | null;
    reversed_by: { id: number; name: string; email: string } | null;
    can_revert: boolean;
};

type ManualReferralProgressAdjustment = {
    id: number;
    level: number;
    amount_usd: string;
    admin_note: string | null;
    created_at: string | null;
    created_by: { id: number; name: string; email: string } | null;
};

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 parsePositiveAmount(raw: string): number | null {
    const trimmed = raw.trim().replace(',', '.');
    if (trimmed === '') {
        return null;
    }

    const n = Number.parseFloat(trimmed);

    return Number.isFinite(n) && n >= 0.01 ? n : null;
}

type ReferralEarningsProgress = {
    direct_earned_usd: string;
    indirect_earned_usd: string;
    direct_limit_usd: string | null;
    indirect_limit_usd: string | null;
};

function ReferralLevelProgress({
    description,
    earnedUsd,
    label,
    limitUsd,
}: {
    description: string;
    earnedUsd: string;
    label: string;
    limitUsd: string | null;
}) {
    const earned = Number.parseFloat(earnedUsd) || 0;
    const limit = limitUsd !== null ? Number.parseFloat(limitUsd) : null;
    const hasLimit = limit !== null && Number.isFinite(limit);
    const percent =
        hasLimit && limit > 0 ? Math.min(100, (earned / limit) * 100) : null;
    const atCap = hasLimit && limit > 0 && earned >= limit;
    const remaining =
        hasLimit && limit > 0 ? Math.max(0, limit - earned) : null;

    return (
        <div className="space-y-3 rounded-lg border border-border/80 bg-muted/20 p-4">
            <div className="flex flex-wrap items-start justify-between gap-2">
                <div>
                    <p className="font-medium text-sm">{label}</p>
                    <p className="text-muted-foreground text-xs leading-relaxed">{description}</p>
                </div>
                {atCap ? (
                    <span className="rounded-full bg-amber-500/15 px-2.5 py-0.5 text-xs font-medium text-amber-700 dark:text-amber-400">
                        Tope alcanzado
                    </span>
                ) : null}
            </div>
            <div className="flex flex-wrap items-baseline justify-between gap-2">
                <p className="text-lg font-semibold tabular-nums">
                    US$ {formatUsdDisplay(earnedUsd)}
                </p>
                {hasLimit ? (
                    <p className="text-muted-foreground text-sm tabular-nums">
                        de US$ {formatUsdDisplay(limitUsd!)} máx.
                    </p>
                ) : (
                    <p className="text-muted-foreground text-sm">Sin tope configurado</p>
                )}
            </div>
            {hasLimit && limit > 0 ? (
                <>
                    <div className="h-2 overflow-hidden rounded-full bg-muted">
                        <div
                            className={cn(
                                'h-full rounded-full transition-[width]',
                                atCap ? 'bg-amber-500' : 'bg-primary',
                            )}
                            style={{ width: `${percent ?? 0}%` }}
                        />
                    </div>
                    <p className="text-muted-foreground text-xs tabular-nums">
                        {atCap
                            ? 'No recibirá más bonos en este nivel.'
                            : `Quedan US$ ${formatUsdDisplay(remaining ?? 0)} disponibles (${(percent ?? 0).toFixed(1)}% usado).`}
                    </p>
                </>
            ) : hasLimit && limit === 0 ? (
                <p className="text-muted-foreground text-xs">
                    El tope global está en US$ 0: no se pagan bonos en este nivel.
                </p>
            ) : null}
        </div>
    );
}

type BalanceConsolidationPreview = {
    has_work: boolean;
    total_withdrawable_usd: string;
    container_balance_before_usd: string;
    container_balance_after_usd: string;
    actions: Array<{
        investment_id: number;
        txid: string;
        amount_usd: string;
        description: string;
    }>;
};

type Props = {
    user: {
        id: number;
        first_name: string;
        last_name: string;
        email: string;
        contact_number: string;
        country: string;
        is_admin: boolean;
        referral_program_enabled: boolean;
        jabes_women_enabled: boolean;
        access_blocked: boolean;
        blocked_at: string | null;
        can_toggle_access_block: boolean;
        can_set_password: boolean;
        can_manage_manual_referrer: boolean;
        can_impersonate: boolean;
        referral_code: string;
        referrer: ReferrerRow | null;
        direct_referrals: ReferrerRow[];
        withdrawable_balance_usd: string;
    };
    referral_earnings_progress: ReferralEarningsProgress;
    manual_balance_credits: ManualBalanceCredit[];
    manual_referral_progress_adjustments: ManualReferralProgressAdjustment[];
    balance_consolidation_preview: BalanceConsolidationPreview;
};

export default function AdminUserEdit({
    user,
    referral_earnings_progress,
    manual_balance_credits,
    manual_referral_progress_adjustments,
    balance_consolidation_preview,
}: Props) {
    const auth = usePage().props.auth.user as AuthUser;
    const pageErrors = usePage<{ errors?: Record<string, string | string[] | undefined> }>().props.errors;
    const isSelf = auth.id === user.id;

    const form = useForm({
        first_name: user.first_name,
        last_name: user.last_name,
        email: user.email,
        contact_number: user.contact_number,
        country: user.country,
        referral_program_enabled: user.referral_program_enabled,
        jabes_women_enabled: user.jabes_women_enabled,
        access_blocked: user.access_blocked,
        referred_by_user_id: (user.referrer?.id ?? '') as number | '',
        password: '',
        password_confirmation: '',
    });

    const [saveConfirmOpen, setSaveConfirmOpen] = useState(false);
    const [impersonateConfirmOpen, setImpersonateConfirmOpen] = useState(false);
    const [detachReferralOpen, setDetachReferralOpen] = useState(false);
    const [detachReferralTarget, setDetachReferralTarget] = useState<ReferrerRow | null>(null);
    const [referrerSearchQuery, setReferrerSearchQuery] = useState('');
    const [referrerSuggestions, setReferrerSuggestions] = useState<ReferrerRow[]>([]);
    const [directReferralSearchQuery, setDirectReferralSearchQuery] = useState('');
    const [directReferralSuggestions, setDirectReferralSuggestions] = useState<ReferrerRow[]>([]);
    const [chosenReferrerDisplay, setChosenReferrerDisplay] = useState<ReferrerRow | null>(
        user.referrer,
    );
    const [directReferralAttaching, setDirectReferralAttaching] = useState(false);
    const [manualBalanceConfirmOpen, setManualBalanceConfirmOpen] = useState(false);
    const [manualReferralConfirmOpen, setManualReferralConfirmOpen] = useState(false);
    const [revertCreditOpen, setRevertCreditOpen] = useState(false);
    const [revertCreditTarget, setRevertCreditTarget] = useState<ManualBalanceCredit | null>(null);
    const [revertCreditProcessing, setRevertCreditProcessing] = useState(false);
    const [consolidateConfirmOpen, setConsolidateConfirmOpen] = useState(false);
    const [consolidateProcessing, setConsolidateProcessing] = useState(false);
    const [withdrawConfirmOpen, setWithdrawConfirmOpen] = useState(false);

    const navSections = useMemo(() => {
        const items: { id: SectionId; label: string; icon: LucideIcon }[] = [
            { id: 'perfil', label: 'Datos de la cuenta', icon: User },
            { id: 'jabes_women', label: 'JabesWomen', icon: Sparkles },
        ];

        items.push({
            id: 'programa_referidos',
            label: 'Programa de referidos',
            icon: Share2,
        });
        items.push({ id: 'referidor', label: 'Referidor', icon: UserSearch });
        if (user.can_manage_manual_referrer) {
            items.push({
                id: 'referidos_directos',
                label: 'Referidos directos',
                icon: Users,
            });
        }

        if (!user.is_admin) {
            items.push({ id: 'acceso', label: 'Acceso al portal', icon: Shield });
        }

        items.push({ id: 'balance', label: 'Balance y retiros', icon: Wallet });

        return items;
    }, [user.is_admin, user.can_manage_manual_referrer]);

    const [activeSection, setActiveSection] = useState<SectionId>(navSections[0]?.id ?? 'perfil');

    const activeMeta = navSections.find((s) => s.id === activeSection) ?? navSections[0]!;
    const showProfileSaveBar = activeSection !== 'balance';

    const referralDetachForm = useForm({});

    const manualBalanceForm = useForm({
        amount: '',
        note: '',
    });

    const manualWithdrawForm = useForm({
        amount: '',
    });

    const manualReferralForm = useForm({
        level: '1' as '1' | '2',
        amount: '',
        note: '',
    });

    const currentWithdrawableUsd = Number.parseFloat(user.withdrawable_balance_usd) || 0;
    const creditAmountUsd = parsePositiveAmount(manualBalanceForm.data.amount);
    const withdrawAmountUsd = parsePositiveAmount(manualWithdrawForm.data.amount);
    const referralAdjustAmountUsd = parsePositiveAmount(manualReferralForm.data.amount);
    const projectedWithdrawableUsd =
        creditAmountUsd !== null ? currentWithdrawableUsd + creditAmountUsd : null;
    const projectedWithdrawableAfterWithdrawUsd =
        withdrawAmountUsd !== null ? currentWithdrawableUsd - withdrawAmountUsd : null;

    const currentDirectProgressUsd =
        Number.parseFloat(referral_earnings_progress.direct_earned_usd) || 0;
    const currentIndirectProgressUsd =
        Number.parseFloat(referral_earnings_progress.indirect_earned_usd) || 0;
    const currentReferralProgressUsd =
        manualReferralForm.data.level === '1'
            ? currentDirectProgressUsd
            : currentIndirectProgressUsd;
    const projectedReferralProgressUsd =
        referralAdjustAmountUsd !== null
            ? currentReferralProgressUsd + referralAdjustAmountUsd
            : null;

    useEffect(() => {
        const q = directReferralSearchQuery.trim();
        if (q.length < 2) {
            setDirectReferralSuggestions([]);

            return;
        }

        const handle = window.setTimeout(() => {
            const excludeExtra = user.direct_referrals.map((r) => r.id).join(',');
            const params = new URLSearchParams({
                q,
                exclude: String(user.id),
                ...(excludeExtra !== '' ? { exclude_ids: excludeExtra } : {}),
            });
            fetch(`/admin/usuarios/referidor-sugerencias?${params}`, {
                credentials: 'same-origin',
                headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
            })
                .then((res) => res.json())
                .then((data: { users?: ReferrerRow[] }) =>
                    setDirectReferralSuggestions(data.users ?? []),
                )
                .catch(() => setDirectReferralSuggestions([]));
        }, 320);

        return () => window.clearTimeout(handle);
    }, [directReferralSearchQuery, user.id, user.direct_referrals.map((r) => r.id).join(',')]);

    useEffect(() => {
        const q = referrerSearchQuery.trim();
        if (q.length < 2) {
            setReferrerSuggestions([]);

            return;
        }

        const handle = window.setTimeout(() => {
            const params = new URLSearchParams({ q, exclude: String(user.id) });
            fetch(`/admin/usuarios/referidor-sugerencias?${params}`, {
                credentials: 'same-origin',
                headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
            })
                .then((res) => res.json())
                .then((data: { users?: ReferrerRow[] }) => setReferrerSuggestions(data.users ?? []))
                .catch(() => setReferrerSuggestions([]));
        }, 320);

        return () => window.clearTimeout(handle);
    }, [referrerSearchQuery, user.id]);

    useEffect(() => {
        if (!navSections.some((s) => s.id === activeSection)) {
            setActiveSection(navSections[0]?.id ?? 'perfil');
        }
    }, [navSections, activeSection]);

    const initialReferrerId = user.referrer?.id ?? null;
    const currentReferrerId =
        form.data.referred_by_user_id === '' ? null : form.data.referred_by_user_id;
    const referrerChanged = currentReferrerId !== initialReferrerId;

    function pickReferrer(row: ReferrerRow) {
        form.setData('referred_by_user_id', row.id);
        setChosenReferrerDisplay(row);
        setReferrerSearchQuery('');
        setReferrerSuggestions([]);
    }

    function clearReferrer() {
        form.setData('referred_by_user_id', '');
        setChosenReferrerDisplay(null);
        setReferrerSearchQuery('');
        setReferrerSuggestions([]);
    }

    function attachDirectReferral(row: ReferrerRow) {
        setDirectReferralAttaching(true);
        router.post(
            `/admin/usuarios/${user.id}/referidos-manuales`,
            { referred_user_id: row.id },
            {
                preserveScroll: true,
                onFinish: () => setDirectReferralAttaching(false),
                onSuccess: () => {
                    setDirectReferralSearchQuery('');
                    setDirectReferralSuggestions([]);
                },
            },
        );
    }

    function openDetachReferral(row: ReferrerRow) {
        setDetachReferralTarget(row);
        setDetachReferralOpen(true);
    }

    function executeDetachReferral() {
        if (!detachReferralTarget) {
            return;
        }

        referralDetachForm.delete(
            `/admin/usuarios/${user.id}/referidos-manuales/${detachReferralTarget.id}`,
            {
                preserveScroll: true,
                onFinish: () => {
                    setDetachReferralOpen(false);
                    setDetachReferralTarget(null);
                },
            },
        );
    }

    function submit(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        setSaveConfirmOpen(true);
    }

    function executeSave() {
        form.patch(`/admin/usuarios/${user.id}`, {
            preserveScroll: true,
            onFinish: () => setSaveConfirmOpen(false),
            onSuccess: () => {
                form.setData('password', '');
                form.setData('password_confirmation', '');
            },
        });
    }

    function executeStartImpersonation() {
        router.post(`/admin/usuarios/${user.id}/impersonar`, undefined, {
            onFinish: () => setImpersonateConfirmOpen(false),
        });
    }

    function requestManualBalanceCredit() {
        if (creditAmountUsd === null) {
            return;
        }

        setManualBalanceConfirmOpen(true);
    }

    function executeManualBalanceCredit() {
        if (creditAmountUsd === null) {
            return;
        }

        manualBalanceForm.post(`/admin/usuarios/${user.id}/balance-manual`, {
            preserveScroll: true,
            onFinish: () => setManualBalanceConfirmOpen(false),
            onSuccess: () => {
                manualBalanceForm.setData({ amount: '', note: '' });
            },
        });
    }

    function requestManualReferralProgress() {
        if (referralAdjustAmountUsd === null) {
            return;
        }

        setManualReferralConfirmOpen(true);
    }

    function executeManualReferralProgress() {
        if (referralAdjustAmountUsd === null) {
            return;
        }

        manualReferralForm.post(`/admin/usuarios/${user.id}/referidos-progreso-manual`, {
            preserveScroll: true,
            onFinish: () => setManualReferralConfirmOpen(false),
            onSuccess: () => {
                manualReferralForm.setData({ level: '1', amount: '', note: '' });
            },
        });
    }

    function requestRevertManualBalance(credit: ManualBalanceCredit) {
        setRevertCreditTarget(credit);
        setRevertCreditOpen(true);
    }

    function executeRevertManualBalance() {
        if (revertCreditTarget === null) {
            return;
        }

        setRevertCreditProcessing(true);

        router.post(
            `/admin/usuarios/${user.id}/balance-manual/${revertCreditTarget.id}/revertir`,
            undefined,
            {
                preserveScroll: true,
                onFinish: () => {
                    setRevertCreditProcessing(false);
                    setRevertCreditOpen(false);
                    setRevertCreditTarget(null);
                },
            },
        );
    }

    function requestManualWithdraw() {
        if (withdrawAmountUsd === null) {
            return;
        }

        setWithdrawConfirmOpen(true);
    }

    function executeManualWithdraw() {
        if (withdrawAmountUsd === null) {
            return;
        }

        manualWithdrawForm.post(`/admin/usuarios/${user.id}/retiro`, {
            preserveScroll: true,
            onFinish: () => setWithdrawConfirmOpen(false),
            onSuccess: () => {
                manualWithdrawForm.setData({ amount: '' });
            },
        });
    }

    function executeConsolidateBalance() {
        setConsolidateProcessing(true);

        router.post(`/admin/usuarios/${user.id}/consolidar-balance`, undefined, {
            preserveScroll: true,
            onFinish: () => {
                setConsolidateProcessing(false);
                setConsolidateConfirmOpen(false);
            },
        });
    }

    const name = `${user.first_name} ${user.last_name}`.trim();

    return (
        <>
            <ConfirmActionModal
                cancelLabel="Seguir editando"
                confirmLabel="Sí, guardar"
                description="Se aplicarán los cambios al usuario en el sistema."
                open={saveConfirmOpen}
                processing={form.processing}
                title="¿Guardar cambios del usuario?"
                onConfirm={executeSave}
                onOpenChange={setSaveConfirmOpen}
            >
                <p className="text-sm text-muted-foreground">
                    Correo: <strong className="text-foreground">{form.data.email}</strong>
                    {user.can_set_password && form.data.password !== '' ? (
                        <span className="mt-2 block text-xs font-medium text-amber-600 dark:text-amber-500">
                            Se establecerá una nueva contraseña para esta cuenta.
                        </span>
                    ) : null}
                    {form.data.access_blocked ? (
                        <span className="mt-2 block text-destructive text-xs font-medium">
                            Esta cuenta quedará con acceso bloqueado hasta que desactives la suspensión.
                        </span>
                    ) : null}
                    {user.can_manage_manual_referrer && referrerChanged ? (
                        <span className="mt-2 block text-xs font-medium text-amber-600 dark:text-amber-500">
                            Se actualizará la relación de referido (referidor manual).
                        </span>
                    ) : null}
                </p>
            </ConfirmActionModal>

            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, impersonar"
                description="Abrirá el portal del inversionista con la sesión de este usuario. No podrá realizar cambios ni operaciones hasta salir de la impersonación."
                open={impersonateConfirmOpen}
                processing={false}
                title={`¿Impersonar a ${name} en modo lectura?`}
                onConfirm={executeStartImpersonation}
                onOpenChange={setImpersonateConfirmOpen}
            >
                <p className="text-sm text-muted-foreground">
                    Correo: <strong className="text-foreground">{user.email}</strong>
                </p>
            </ConfirmActionModal>

            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, desvincular"
                description="El usuario dejará de figurar como referido directo de esta cuenta. No borra la cuenta ni modifica movimientos pasados."
                open={detachReferralOpen}
                processing={referralDetachForm.processing}
                title={
                    detachReferralTarget
                        ? `¿Quitar a ${detachReferralTarget.name} como referido?`
                        : '¿Quitar referido?'
                }
                onConfirm={executeDetachReferral}
                onOpenChange={(open) => {
                    setDetachReferralOpen(open);
                    if (!open) {
                        setDetachReferralTarget(null);
                    }
                }}
            >
                {detachReferralTarget ? (
                    <p className="text-sm text-muted-foreground">
                        Correo:{' '}
                        <strong className="text-foreground">{detachReferralTarget.email}</strong>
                    </p>
                ) : null}
            </ConfirmActionModal>

            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, revertir acreditación"
                description="Se descontará el monto del saldo retirable del usuario y quedará registrada la reversión en movimientos."
                open={revertCreditOpen}
                processing={revertCreditProcessing}
                title={
                    revertCreditTarget
                        ? `¿Revertir acreditación de US$ ${formatUsdDisplay(revertCreditTarget.amount_usd)}?`
                        : '¿Revertir acreditación?'
                }
                onConfirm={executeRevertManualBalance}
                onOpenChange={(open) => {
                    setRevertCreditOpen(open);
                    if (!open) {
                        setRevertCreditTarget(null);
                    }
                }}
            >
                {revertCreditTarget ? (
                    <div className="space-y-2 text-sm text-muted-foreground">
                        <p>
                            <span className="font-medium text-foreground">Fecha:</span>{' '}
                            {formatShortDatetime(revertCreditTarget.created_at)}
                        </p>
                        {revertCreditTarget.admin_note ? (
                            <p>
                                <span className="font-medium text-foreground">Nota:</span>{' '}
                                {revertCreditTarget.admin_note}
                            </p>
                        ) : null}
                    </div>
                ) : null}
            </ConfirmActionModal>

            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, acreditar saldo"
                description="El monto se sumará al saldo retirable del usuario y quedará registrado en su libro de movimientos."
                open={manualBalanceConfirmOpen}
                processing={manualBalanceForm.processing}
                title="¿Confirmar acreditación de saldo?"
                onConfirm={executeManualBalanceCredit}
                onOpenChange={setManualBalanceConfirmOpen}
            >
                <div className="space-y-2 text-sm text-muted-foreground">
                    <p>
                        <span className="font-medium text-foreground">Usuario:</span> {name} ·{' '}
                        {user.email}
                    </p>
                    <p>
                        <span className="font-medium text-foreground">Saldo actual:</span>{' '}
                        <span className="tabular-nums text-foreground">
                            US$ {formatUsdDisplay(currentWithdrawableUsd)}
                        </span>
                    </p>
                    <p>
                        <span className="font-medium text-foreground">Monto a acreditar:</span>{' '}
                        <span className="tabular-nums font-semibold text-primary">
                            + US$ {formatUsdDisplay(creditAmountUsd ?? 0)}
                        </span>
                    </p>
                    {projectedWithdrawableUsd !== null ? (
                        <p>
                            <span className="font-medium text-foreground">Nuevo saldo:</span>{' '}
                            <span className="tabular-nums font-semibold text-foreground">
                                US$ {formatUsdDisplay(projectedWithdrawableUsd)}
                            </span>
                        </p>
                    ) : null}
                    {manualBalanceForm.data.note.trim() !== '' ? (
                        <p>
                            <span className="font-medium text-foreground">Nota:</span>{' '}
                            {manualBalanceForm.data.note.trim()}
                        </p>
                    ) : null}
                </div>
            </ConfirmActionModal>

            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, consolidar saldo"
                description="Se moverá el saldo retirable disperso en inversiones al balance general del usuario. No se elimina información histórica."
                open={consolidateConfirmOpen}
                processing={consolidateProcessing}
                title="¿Consolidar saldo retirable?"
                onConfirm={executeConsolidateBalance}
                onOpenChange={setConsolidateConfirmOpen}
            >
                <div className="space-y-3 text-sm text-muted-foreground">
                    <p>
                        <span className="font-medium text-foreground">Saldo retirable total:</span>{' '}
                        <span className="tabular-nums text-foreground">
                            US$ {formatUsdDisplay(balance_consolidation_preview.total_withdrawable_usd)}
                        </span>
                    </p>
                    <p>
                        <span className="font-medium text-foreground">Balance general actual:</span>{' '}
                        <span className="tabular-nums text-foreground">
                            US$ {formatUsdDisplay(balance_consolidation_preview.container_balance_before_usd)}
                        </span>
                        {' → '}
                        <span className="tabular-nums font-semibold text-primary">
                            US$ {formatUsdDisplay(balance_consolidation_preview.container_balance_after_usd)}
                        </span>
                    </p>
                    {balance_consolidation_preview.actions.length > 0 ? (
                        <ul className="max-h-48 space-y-2 overflow-y-auto rounded-md border bg-muted/30 p-3 text-xs leading-relaxed">
                            {balance_consolidation_preview.actions.map((action) => (
                                <li key={`${action.investment_id}-${action.txid}`}>
                                    {action.description}
                                </li>
                            ))}
                        </ul>
                    ) : null}
                </div>
            </ConfirmActionModal>

            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, registrar retiro"
                confirmVariant="destructive"
                description="Se descontará el monto del balance retirable del usuario y quedará registrado como retiro en movimientos."
                open={withdrawConfirmOpen}
                processing={manualWithdrawForm.processing}
                title="¿Registrar retiro administrativo?"
                onConfirm={executeManualWithdraw}
                onOpenChange={setWithdrawConfirmOpen}
            >
                <div className="space-y-2 text-sm text-muted-foreground">
                    <p>
                        <span className="font-medium text-foreground">Usuario:</span> {name} ·{' '}
                        {user.email}
                    </p>
                    <p>
                        <span className="font-medium text-foreground">Saldo actual:</span>{' '}
                        <span className="tabular-nums text-foreground">
                            US$ {formatUsdDisplay(currentWithdrawableUsd)}
                        </span>
                    </p>
                    <p>
                        <span className="font-medium text-foreground">Monto a retirar:</span>{' '}
                        <span className="tabular-nums font-semibold text-destructive">
                            − US$ {formatUsdDisplay(withdrawAmountUsd ?? 0)}
                        </span>
                    </p>
                    {projectedWithdrawableAfterWithdrawUsd !== null ? (
                        <p>
                            <span className="font-medium text-foreground">Nuevo saldo:</span>{' '}
                            <span className="tabular-nums font-semibold text-foreground">
                                US$ {formatUsdDisplay(projectedWithdrawableAfterWithdrawUsd)}
                            </span>
                        </p>
                    ) : null}
                </div>
            </ConfirmActionModal>

            <ConfirmActionModal
                cancelLabel="Cancelar"
                confirmLabel="Sí, registrar ajuste"
                description="El monto se sumará al progreso de ganancias por referidos del nivel elegido. No se acreditará saldo retirable ni capital."
                open={manualReferralConfirmOpen}
                processing={manualReferralForm.processing}
                title="¿Confirmar ajuste de progreso de referidos?"
                onConfirm={executeManualReferralProgress}
                onOpenChange={setManualReferralConfirmOpen}
            >
                <div className="space-y-2 text-sm text-muted-foreground">
                    <p>
                        <span className="font-medium text-foreground">Usuario:</span> {name} ·{' '}
                        {user.email}
                    </p>
                    <p>
                        <span className="font-medium text-foreground">Nivel:</span>{' '}
                        {manualReferralForm.data.level === '1'
                            ? 'Directas (L1)'
                            : 'Indirectas (L2)'}
                    </p>
                    <p>
                        <span className="font-medium text-foreground">Progreso actual:</span>{' '}
                        <span className="tabular-nums text-foreground">
                            US$ {formatUsdDisplay(currentReferralProgressUsd)}
                        </span>
                    </p>
                    <p>
                        <span className="font-medium text-foreground">Monto a sumar:</span>{' '}
                        <span className="tabular-nums font-semibold text-primary">
                            + US$ {formatUsdDisplay(referralAdjustAmountUsd ?? 0)}
                        </span>
                    </p>
                    {projectedReferralProgressUsd !== null ? (
                        <p>
                            <span className="font-medium text-foreground">Nuevo progreso:</span>{' '}
                            <span className="tabular-nums font-semibold text-foreground">
                                US$ {formatUsdDisplay(projectedReferralProgressUsd)}
                            </span>
                        </p>
                    ) : null}
                    {manualReferralForm.data.note.trim() !== '' ? (
                        <p>
                            <span className="font-medium text-foreground">Nota:</span>{' '}
                            {manualReferralForm.data.note.trim()}
                        </p>
                    ) : null}
                </div>
            </ConfirmActionModal>

            <Head title={`Editar: ${name}`} />

            <div className="mx-auto max-w-6xl space-y-8 p-4">
                <Link
                    className="text-muted-foreground hover:text-foreground inline-flex items-center gap-2 text-sm"
                    href="/admin/usuarios"
                >
                    <ArrowLeft className="size-4" />
                    Directorio de usuarios
                </Link>

                <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
                    <Heading
                        title="Editar usuario"
                        description={
                            user.is_admin
                                ? `Administrador · ${user.email}. El rol no se cambia desde aquí.${
                                      isSelf ? ' Estás editando tu propio perfil administrativo.' : ''
                                  }`
                                : `Inversionista · ${user.email}`
                        }
                    />
                    {user.can_impersonate ? (
                        <Button
                            type="button"
                            variant="outline"
                            className="shrink-0"
                            onClick={() => setImpersonateConfirmOpen(true)}
                        >
                            <Eye className="size-4" aria-hidden />
                            Impersonar (solo lectura)
                        </Button>
                    ) : null}
                </div>

                <div className="flex flex-col gap-8 lg:flex-row lg:items-start lg:gap-10">
                    <aside className="lg:sticky lg:top-20 lg:w-52 lg:shrink-0">
                        <p className="text-muted-foreground mb-3 hidden text-xs font-medium tracking-wide uppercase lg:block">
                            Secciones
                        </p>
                        <nav
                            aria-label="Secciones del usuario"
                            role="tablist"
                            className="flex gap-2 overflow-x-auto pb-1 lg:flex-col lg:gap-0.5 lg:overflow-visible lg:pb-0"
                        >
                            {navSections.map(({ id, label, icon: Icon }) => (
                                <button
                                    key={id}
                                    type="button"
                                    id={`tab-${id}`}
                                    role="tab"
                                    aria-selected={activeSection === id}
                                    aria-controls="user-edit-panel"
                                    onClick={() => setActiveSection(id)}
                                    className={cn(
                                        'inline-flex shrink-0 items-center gap-2 rounded-lg px-3 py-2 text-left text-sm transition-colors lg:w-full',
                                        activeSection === id
                                            ? 'bg-muted text-foreground font-medium'
                                            : 'text-muted-foreground hover:bg-muted/60 hover:text-foreground',
                                    )}
                                >
                                    <Icon className="size-4 shrink-0 opacity-70" aria-hidden />
                                    {label}
                                </button>
                            ))}
                        </nav>
                    </aside>

                    <div className="min-w-0 flex-1">
                        {activeSection === 'balance' ? (
                            <div
                                id="user-edit-panel"
                                role="tabpanel"
                                aria-labelledby="tab-balance"
                                key="balance"
                                className="space-y-6"
                            >
                                <SettingsSection
                                    title="Balance del usuario"
                                    description="Saldo retirable consolidado del usuario (ganancias, referidos, ajustes y depósitos disponibles según las reglas del fondo)."
                                    icon={Wallet}
                                >
                                    <div className="rounded-lg border bg-muted/40 p-4">
                                        <p className="text-muted-foreground text-xs font-medium uppercase tracking-wide">
                                            Saldo retirable actual
                                        </p>
                                        <p className="mt-1 text-2xl font-bold tabular-nums text-foreground">
                                            US$ {formatUsdDisplay(currentWithdrawableUsd)}
                                        </p>
                                    </div>
                                </SettingsSection>

                                <SettingsSection
                                    title="Consolidar saldo retirable"
                                    description="Mueve saldo retirable que aún está en inversiones individuales hacia el balance general del usuario. Útil en producción para alinear cuentas legacy."
                                    icon={Layers}
                                >
                                    <div className="grid gap-3 sm:grid-cols-2">
                                        <div className="rounded-lg border bg-muted/40 p-4">
                                            <p className="text-muted-foreground text-xs font-medium uppercase tracking-wide">
                                                Balance general (contenedor)
                                            </p>
                                            <p className="mt-1 text-lg font-semibold tabular-nums">
                                                US$ {formatUsdDisplay(balance_consolidation_preview.container_balance_before_usd)}
                                            </p>
                                        </div>
                                        <div className="border-primary/30 bg-primary/10 rounded-lg border p-4">
                                            <p className="text-muted-foreground text-xs font-medium uppercase tracking-wide">
                                                Tras consolidar
                                            </p>
                                            <p className="text-primary mt-1 text-lg font-semibold tabular-nums">
                                                US$ {formatUsdDisplay(balance_consolidation_preview.container_balance_after_usd)}
                                            </p>
                                        </div>
                                    </div>

                                    {balance_consolidation_preview.has_work ? (
                                        <ul className="space-y-2 rounded-lg border bg-muted/20 p-4 text-sm leading-relaxed">
                                            {balance_consolidation_preview.actions.map((action) => (
                                                <li
                                                    key={`${action.investment_id}-${action.txid}`}
                                                    className="text-muted-foreground"
                                                >
                                                    {action.description}
                                                </li>
                                            ))}
                                        </ul>
                                    ) : (
                                        <p className="text-muted-foreground rounded-lg border border-dashed p-4 text-sm">
                                            No hay saldo retirable disperso que consolidar en este momento.
                                        </p>
                                    )}

                                    <Button
                                        disabled={!balance_consolidation_preview.has_work || consolidateProcessing}
                                        type="button"
                                        variant="secondary"
                                        onClick={() => setConsolidateConfirmOpen(true)}
                                    >
                                        {consolidateProcessing ? 'Consolidando…' : 'Consolidar saldo retirable'}
                                    </Button>
                                </SettingsSection>

                                <SettingsSection
                                    title="Registrar retiro"
                                    description="Descuenta saldo retirable del balance general del usuario. No crea solicitud ni requiere TXID de envío."
                                    icon={ArrowDownToLine}
                                >
                                    <form
                                        className="space-y-4"
                                        onSubmit={(e) => {
                                            e.preventDefault();
                                            requestManualWithdraw();
                                        }}
                                    >
                                        <div className="grid gap-2 sm:max-w-xs">
                                            <Label htmlFor="manual_withdraw_amount">
                                                Monto a retirar (USD)
                                            </Label>
                                            <Input
                                                autoComplete="off"
                                                disabled={manualWithdrawForm.processing}
                                                enterKeyHint="done"
                                                id="manual_withdraw_amount"
                                                inputMode="decimal"
                                                placeholder="Ej. 50.00"
                                                required
                                                type="text"
                                                value={manualWithdrawForm.data.amount}
                                                onChange={(e) =>
                                                    manualWithdrawForm.setData('amount', e.target.value)
                                                }
                                            />
                                            <InputError message={manualWithdrawForm.errors.amount} />
                                        </div>
                                        {projectedWithdrawableAfterWithdrawUsd !== null ? (
                                            <p className="text-muted-foreground text-sm tabular-nums">
                                                Saldo estimado después del retiro:{' '}
                                                <span className="font-medium text-foreground">
                                                    US$ {formatUsdDisplay(projectedWithdrawableAfterWithdrawUsd)}
                                                </span>
                                            </p>
                                        ) : null}
                                        <Button
                                            disabled={
                                                manualWithdrawForm.processing ||
                                                withdrawAmountUsd === null
                                            }
                                            type="submit"
                                            variant="destructive"
                                        >
                                            {manualWithdrawForm.processing
                                                ? 'Procesando…'
                                                : 'Continuar a confirmación'}
                                        </Button>
                                    </form>
                                </SettingsSection>

                                <SettingsSection
                                    title="Acreditar saldo"
                                    description="Suma saldo retirable a la cuenta del usuario. La operación queda registrada en movimientos como ajuste administrativo (acción independiente de guardar el perfil)."
                                    icon={Wallet}
                                >
                                    <div className="grid gap-3 sm:grid-cols-2">
                                        <div className="rounded-lg border bg-muted/40 p-4">
                                            <p className="text-muted-foreground text-xs font-medium uppercase tracking-wide">
                                                Saldo retirable actual
                                            </p>
                                            <p className="mt-1 text-2xl font-bold tabular-nums text-foreground">
                                                US$ {formatUsdDisplay(currentWithdrawableUsd)}
                                            </p>
                                        </div>
                                        <div className="border-primary/30 bg-primary/10 rounded-lg border p-4">
                                            <p className="text-muted-foreground text-xs font-medium uppercase tracking-wide">
                                                Saldo después de acreditar
                                            </p>
                                            <p className="text-primary mt-1 text-2xl font-bold tabular-nums">
                                                {projectedWithdrawableUsd !== null
                                                    ? `US$ ${formatUsdDisplay(projectedWithdrawableUsd)}`
                                                    : '—'}
                                            </p>
                                            <p className="text-muted-foreground mt-1 text-xs">
                                                {creditAmountUsd !== null
                                                    ? `Incluye + US$ ${formatUsdDisplay(creditAmountUsd)}`
                                                    : 'Ingresa un monto para ver la proyección'}
                                            </p>
                                        </div>
                                    </div>

                                    <form
                                        className="space-y-4"
                                        onSubmit={(e) => {
                                            e.preventDefault();
                                            requestManualBalanceCredit();
                                        }}
                                    >
                                        <div className="grid gap-2 sm:max-w-xs">
                                            <Label htmlFor="manual_balance_amount">
                                                Monto a acreditar (USD)
                                            </Label>
                                            <Input
                                                autoComplete="off"
                                                disabled={manualBalanceForm.processing}
                                                enterKeyHint="done"
                                                id="manual_balance_amount"
                                                inputMode="decimal"
                                                placeholder="Ej. 100.00"
                                                required
                                                type="text"
                                                value={manualBalanceForm.data.amount}
                                                onChange={(e) =>
                                                    manualBalanceForm.setData('amount', e.target.value)
                                                }
                                            />
                                            <InputError message={manualBalanceForm.errors.amount} />
                                        </div>
                                        <div className="grid gap-2">
                                            <Label htmlFor="manual_balance_note">
                                                Nota interna (opcional)
                                            </Label>
                                            <Input
                                                disabled={manualBalanceForm.processing}
                                                id="manual_balance_note"
                                                maxLength={500}
                                                placeholder="Motivo del ajuste…"
                                                value={manualBalanceForm.data.note}
                                                onChange={(e) =>
                                                    manualBalanceForm.setData('note', e.target.value)
                                                }
                                            />
                                            <InputError message={manualBalanceForm.errors.note} />
                                        </div>
                                        <Button
                                            disabled={
                                                manualBalanceForm.processing ||
                                                creditAmountUsd === null
                                            }
                                            type="submit"
                                        >
                                            {manualBalanceForm.processing
                                                ? 'Procesando…'
                                                : 'Continuar a confirmación'}
                                        </Button>
                                    </form>

                                    <div className="space-y-3 border-t border-border/60 pt-6">
                                        <div>
                                            <p className="font-medium text-sm">
                                                Historial de acreditaciones manuales
                                            </p>
                                            <p className="text-muted-foreground text-xs leading-relaxed">
                                                Ajustes administrativos aplicados a este usuario.
                                                Puede revertir las que sigan vigentes si el saldo
                                                aún está disponible.
                                            </p>
                                        </div>

                                        {manual_balance_credits.length === 0 ? (
                                            <p className="text-muted-foreground rounded-lg border border-dashed p-4 text-sm">
                                                No hay acreditaciones manuales registradas.
                                            </p>
                                        ) : (
                                            <div className="overflow-x-auto rounded-lg border">
                                                <table className="w-full min-w-[640px] text-sm">
                                                    <thead>
                                                        <tr className="border-b bg-muted/40 text-left">
                                                            <th className="px-3 py-2.5 font-medium">
                                                                Fecha
                                                            </th>
                                                            <th className="px-3 py-2.5 font-medium">
                                                                Monto
                                                            </th>
                                                            <th className="px-3 py-2.5 font-medium">
                                                                Nota
                                                            </th>
                                                            <th className="px-3 py-2.5 font-medium">
                                                                Admin
                                                            </th>
                                                            <th className="px-3 py-2.5 font-medium">
                                                                Estado
                                                            </th>
                                                            <th className="px-3 py-2.5 font-medium text-right">
                                                                Acción
                                                            </th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        {manual_balance_credits.map((credit) => (
                                                            <tr
                                                                key={credit.id}
                                                                className="border-b last:border-b-0"
                                                            >
                                                                <td className="text-muted-foreground px-3 py-2.5 tabular-nums">
                                                                    {formatShortDatetime(
                                                                        credit.created_at,
                                                                    )}
                                                                </td>
                                                                <td className="px-3 py-2.5 font-semibold tabular-nums">
                                                                    + US${' '}
                                                                    {formatUsdDisplay(
                                                                        credit.amount_usd,
                                                                    )}
                                                                </td>
                                                                <td className="text-muted-foreground max-w-[200px] truncate px-3 py-2.5">
                                                                    {credit.admin_note ?? '—'}
                                                                </td>
                                                                <td className="text-muted-foreground px-3 py-2.5">
                                                                    {credit.created_by?.name ?? '—'}
                                                                </td>
                                                                <td className="px-3 py-2.5">
                                                                    {credit.reversed_at ? (
                                                                        <div className="space-y-0.5">
                                                                            <Badge variant="outline">
                                                                                Revertida
                                                                            </Badge>
                                                                            <p className="text-muted-foreground text-xs">
                                                                                {formatShortDatetime(
                                                                                    credit.reversed_at,
                                                                                )}
                                                                                {credit.reversed_by
                                                                                    ? ` · ${credit.reversed_by.name}`
                                                                                    : ''}
                                                                            </p>
                                                                        </div>
                                                                    ) : (
                                                                        <Badge variant="secondary">
                                                                            Vigente
                                                                        </Badge>
                                                                    )}
                                                                </td>
                                                                <td className="px-3 py-2.5 text-right">
                                                                    {credit.can_revert ? (
                                                                        <Button
                                                                            type="button"
                                                                            variant="outline"
                                                                            size="sm"
                                                                            onClick={() =>
                                                                                requestRevertManualBalance(
                                                                                    credit,
                                                                                )
                                                                            }
                                                                        >
                                                                            <Undo2
                                                                                className="size-3.5"
                                                                                aria-hidden
                                                                            />
                                                                            Revertir
                                                                        </Button>
                                                                    ) : (
                                                                        <span className="text-muted-foreground text-xs">
                                                                            —
                                                                        </span>
                                                                    )}
                                                                </td>
                                                            </tr>
                                                        ))}
                                                    </tbody>
                                                </table>
                                            </div>
                                        )}
                                    </div>
                                </SettingsSection>
                            </div>
                        ) : (
                            <form className="space-y-6" onSubmit={submit}>
                                <div
                                    id="user-edit-panel"
                                    role="tabpanel"
                                    aria-labelledby={`tab-${activeSection}`}
                                    key={activeSection}
                                >
                                    {activeSection === 'perfil' && (
                                        <SettingsSection
                                            title="Datos de la cuenta"
                                            description="Nombre, correo de acceso y contacto registrados en el sistema para este usuario."
                                            icon={User}
                                        >
                            <div className="grid gap-4 sm:grid-cols-2">
                                <div className="grid gap-2">
                                    <Label htmlFor="first_name">Nombre</Label>
                                    <Input
                                        id="first_name"
                                        name="first_name"
                                        required
                                        value={form.data.first_name}
                                        onChange={(e) => form.setData('first_name', e.target.value)}
                                        disabled={form.processing}
                                    />
                                    <InputError message={form.errors.first_name} />
                                </div>
                                <div className="grid gap-2">
                                    <Label htmlFor="last_name">Apellido</Label>
                                    <Input
                                        id="last_name"
                                        name="last_name"
                                        required
                                        value={form.data.last_name}
                                        onChange={(e) => form.setData('last_name', e.target.value)}
                                        disabled={form.processing}
                                    />
                                    <InputError message={form.errors.last_name} />
                                </div>
                            </div>

                            <div className="grid gap-2">
                                <Label htmlFor="email">Correo electrónico</Label>
                                <Input
                                    id="email"
                                    type="email"
                                    name="email"
                                    autoComplete="off"
                                    required
                                    value={form.data.email}
                                    onChange={(e) => form.setData('email', e.target.value)}
                                    disabled={form.processing}
                                />
                                <InputError message={form.errors.email} />
                                <p className="text-muted-foreground text-xs">
                                    Si modificas el correo, puede requerirse de nuevo verificar la nueva dirección.
                                </p>
                            </div>

                            <div className="grid gap-2">
                                <Label htmlFor="country">País</Label>
                                <Select
                                    value={form.data.country}
                                    onValueChange={(v) => form.setData('country', v)}
                                    disabled={form.processing}
                                >
                                    <SelectTrigger id="country" className="w-full">
                                        <SelectValue placeholder="Selecciona país" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {countryOptions.map((option) => (
                                            <SelectItem key={option.value} value={option.value}>
                                                {option.label}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                <InputError message={form.errors.country} />
                            </div>

                            <div className="grid gap-2">
                                <Label htmlFor="contact_number">Teléfono</Label>
                                <Input
                                    id="contact_number"
                                    inputMode="tel"
                                    autoComplete="off"
                                    name="contact_number"
                                    required
                                    value={form.data.contact_number}
                                    onChange={(e) => form.setData('contact_number', e.target.value)}
                                    placeholder="+00 600 000 000"
                                    disabled={form.processing}
                                />
                                <InputError message={form.errors.contact_number} />
                            </div>

                            {user.can_set_password ? (
                                <div className="space-y-4 border-t pt-6">
                                    <div>
                                        <h3 className="text-sm font-medium">Nueva contraseña (opcional)</h3>
                                        <p className="text-muted-foreground mt-1 text-xs">
                                            Déjalo vacío para no cambiar la contraseña. No disponible para cuentas de
                                            administrador.
                                        </p>
                                    </div>
                                    <div className="grid gap-4 sm:grid-cols-2">
                                        <div className="grid gap-2">
                                            <Label htmlFor="password">Contraseña</Label>
                                            <Input
                                                autoComplete="new-password"
                                                disabled={form.processing}
                                                id="password"
                                                name="password"
                                                type="password"
                                                value={form.data.password}
                                                onChange={(e) => form.setData('password', e.target.value)}
                                            />
                                            <InputError message={form.errors.password} />
                                        </div>
                                        <div className="grid gap-2">
                                            <Label htmlFor="password_confirmation">
                                                Confirmar contraseña
                                            </Label>
                                            <Input
                                                autoComplete="new-password"
                                                disabled={form.processing}
                                                id="password_confirmation"
                                                name="password_confirmation"
                                                type="password"
                                                value={form.data.password_confirmation}
                                                onChange={(e) =>
                                                    form.setData('password_confirmation', e.target.value)
                                                }
                                            />
                                            <InputError message={form.errors.password_confirmation} />
                                        </div>
                                    </div>
                                </div>
                            ) : null}
                                        </SettingsSection>
                                    )}

                                    {activeSection === 'jabes_women' && (
                                        <SettingsSection
                                            title="JabesWomen"
                                            description="Activa la experiencia visual morada de la plataforma, orientada al empoderamiento femenino en inversiones y finanzas."
                                            icon={Sparkles}
                                        >
                                            <ToggleRow
                                                checked={form.data.jabes_women_enabled}
                                                disabled={form.processing}
                                                id="jabes_women_enabled"
                                                onCheckedChange={(v) =>
                                                    form.setData('jabes_women_enabled', v)
                                                }
                                                title="Experiencia JabesWomen habilitada"
                                                description="El usuario verá acentos morados, mensajes de bienvenida y la identidad JabesWomen al iniciar sesión."
                                            />
                                            <InputError message={form.errors.jabes_women_enabled} />
                                        </SettingsSection>
                                    )}

                                    {activeSection === 'programa_referidos' && (
                                        <SettingsSection
                                            title="Programa de referidos"
                                            description="Solo aplica sobre la red, comisiones y acceso al módulo de referidos."
                                            icon={Share2}
                                        >
                                            <ToggleRow
                                                checked={form.data.referral_program_enabled}
                                                disabled={form.processing}
                                                id="referral_program_enabled"
                                                onCheckedChange={(v) =>
                                                    form.setData('referral_program_enabled', v)
                                                }
                                                title="Programa de referidos habilitado"
                                                description="Si está desactivado, no podrá usar el enlace de referidos ni acumular bonos por la red configurada en la plataforma."
                                            />
                                            <InputError message={form.errors.referral_program_enabled} />

                                            <div className="space-y-3 border-t border-border/60 pt-4">
                                                <div>
                                                    <p className="font-medium text-sm">
                                                        Progreso de ganancias por referidos
                                                    </p>
                                                    <p className="text-muted-foreground text-xs leading-relaxed">
                                                        Acumulado hacia el tope global configurado en
                                                        parámetros de inversión (incluye bonos pagados y
                                                        ajustes manuales de progreso).
                                                    </p>
                                                </div>
                                                <ReferralLevelProgress
                                                    description="Bonos por inversiones de referidos directos (nivel 1)."
                                                    earnedUsd={referral_earnings_progress.direct_earned_usd}
                                                    label="Ganancias directas"
                                                    limitUsd={referral_earnings_progress.direct_limit_usd}
                                                />
                                                <ReferralLevelProgress
                                                    description="Bonos por inversiones de referidos indirectos (nivel 2)."
                                                    earnedUsd={referral_earnings_progress.indirect_earned_usd}
                                                    label="Ganancias indirectas"
                                                    limitUsd={referral_earnings_progress.indirect_limit_usd}
                                                />
                                            </div>

                                            <div className="space-y-4 border-t border-border/60 pt-6">
                                                <div>
                                                    <p className="font-medium text-sm">
                                                        Ajuste manual de progreso
                                                    </p>
                                                    <p className="text-muted-foreground text-xs leading-relaxed">
                                                        Suma al registro de ganancias L1 o L2 para el
                                                        tope de referidos. No acredita saldo retirable ni
                                                        modifica el capital del usuario.
                                                    </p>
                                                </div>

                                                <div className="grid gap-3 sm:grid-cols-2">
                                                    <div className="rounded-lg border bg-muted/40 p-4">
                                                        <p className="text-muted-foreground text-xs font-medium uppercase tracking-wide">
                                                            Progreso L1 actual
                                                        </p>
                                                        <p className="mt-1 text-xl font-bold tabular-nums text-foreground">
                                                            US${' '}
                                                            {formatUsdDisplay(currentDirectProgressUsd)}
                                                        </p>
                                                    </div>
                                                    <div className="rounded-lg border bg-muted/40 p-4">
                                                        <p className="text-muted-foreground text-xs font-medium uppercase tracking-wide">
                                                            Progreso L2 actual
                                                        </p>
                                                        <p className="mt-1 text-xl font-bold tabular-nums text-foreground">
                                                            US${' '}
                                                            {formatUsdDisplay(currentIndirectProgressUsd)}
                                                        </p>
                                                    </div>
                                                </div>

                                                <div className="space-y-4">
                                                    <div className="grid gap-2 sm:max-w-xs">
                                                        <Label htmlFor="manual_referral_level">
                                                            Nivel
                                                        </Label>
                                                        <Select
                                                            disabled={manualReferralForm.processing}
                                                            value={manualReferralForm.data.level}
                                                            onValueChange={(v) =>
                                                                manualReferralForm.setData(
                                                                    'level',
                                                                    v as '1' | '2',
                                                                )
                                                            }
                                                        >
                                                            <SelectTrigger id="manual_referral_level">
                                                                <SelectValue />
                                                            </SelectTrigger>
                                                            <SelectContent>
                                                                <SelectItem value="1">
                                                                    Directas (L1)
                                                                </SelectItem>
                                                                <SelectItem value="2">
                                                                    Indirectas (L2)
                                                                </SelectItem>
                                                            </SelectContent>
                                                        </Select>
                                                        <InputError
                                                            message={manualReferralForm.errors.level}
                                                        />
                                                    </div>
                                                    <div className="grid gap-2 sm:max-w-xs">
                                                        <Label htmlFor="manual_referral_amount">
                                                            Monto a sumar (USD)
                                                        </Label>
                                                        <Input
                                                            autoComplete="off"
                                                            disabled={manualReferralForm.processing}
                                                            enterKeyHint="done"
                                                            id="manual_referral_amount"
                                                            inputMode="decimal"
                                                            placeholder="Ej. 50.00"
                                                            type="text"
                                                            value={manualReferralForm.data.amount}
                                                            onChange={(e) =>
                                                                manualReferralForm.setData(
                                                                    'amount',
                                                                    e.target.value,
                                                                )
                                                            }
                                                        />
                                                        <InputError
                                                            message={manualReferralForm.errors.amount}
                                                        />
                                                        {projectedReferralProgressUsd !== null ? (
                                                            <p className="text-muted-foreground text-xs tabular-nums">
                                                                Nuevo progreso{' '}
                                                                {manualReferralForm.data.level === '1'
                                                                    ? 'L1'
                                                                    : 'L2'}
                                                                : US${' '}
                                                                {formatUsdDisplay(
                                                                    projectedReferralProgressUsd,
                                                                )}
                                                            </p>
                                                        ) : null}
                                                    </div>
                                                    <div className="grid gap-2">
                                                        <Label htmlFor="manual_referral_note">
                                                            Nota interna (opcional)
                                                        </Label>
                                                        <Input
                                                            disabled={manualReferralForm.processing}
                                                            id="manual_referral_note"
                                                            maxLength={500}
                                                            placeholder="Motivo del ajuste…"
                                                            value={manualReferralForm.data.note}
                                                            onChange={(e) =>
                                                                manualReferralForm.setData(
                                                                    'note',
                                                                    e.target.value,
                                                                )
                                                            }
                                                        />
                                                        <InputError
                                                            message={manualReferralForm.errors.note}
                                                        />
                                                    </div>
                                                    <Button
                                                        disabled={
                                                            manualReferralForm.processing ||
                                                            referralAdjustAmountUsd === null
                                                        }
                                                        type="button"
                                                        onClick={requestManualReferralProgress}
                                                    >
                                                        {manualReferralForm.processing
                                                            ? 'Procesando…'
                                                            : 'Continuar a confirmación'}
                                                    </Button>
                                                </div>

                                                <div className="space-y-3 border-t border-border/60 pt-4">
                                                    <p className="font-medium text-sm">
                                                        Historial de ajustes manuales
                                                    </p>
                                                    {manual_referral_progress_adjustments.length ===
                                                    0 ? (
                                                        <p className="text-muted-foreground rounded-lg border border-dashed p-4 text-sm">
                                                            No hay ajustes manuales de progreso
                                                            registrados.
                                                        </p>
                                                    ) : (
                                                        <div className="overflow-x-auto rounded-lg border">
                                                            <table className="w-full min-w-[520px] text-sm">
                                                                <thead>
                                                                    <tr className="border-b bg-muted/40 text-left">
                                                                        <th className="px-3 py-2.5 font-medium">
                                                                            Fecha
                                                                        </th>
                                                                        <th className="px-3 py-2.5 font-medium">
                                                                            Nivel
                                                                        </th>
                                                                        <th className="px-3 py-2.5 font-medium">
                                                                            Monto
                                                                        </th>
                                                                        <th className="px-3 py-2.5 font-medium">
                                                                            Nota
                                                                        </th>
                                                                        <th className="px-3 py-2.5 font-medium">
                                                                            Admin
                                                                        </th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody>
                                                                    {manual_referral_progress_adjustments.map(
                                                                        (row) => (
                                                                            <tr
                                                                                key={row.id}
                                                                                className="border-b last:border-b-0"
                                                                            >
                                                                                <td className="text-muted-foreground px-3 py-2.5 tabular-nums">
                                                                                    {formatShortDatetime(
                                                                                        row.created_at,
                                                                                    )}
                                                                                </td>
                                                                                <td className="px-3 py-2.5">
                                                                                    {row.level === 1
                                                                                        ? 'L1'
                                                                                        : 'L2'}
                                                                                </td>
                                                                                <td className="px-3 py-2.5 font-semibold tabular-nums">
                                                                                    + US${' '}
                                                                                    {formatUsdDisplay(
                                                                                        row.amount_usd,
                                                                                    )}
                                                                                </td>
                                                                                <td className="text-muted-foreground max-w-[200px] truncate px-3 py-2.5">
                                                                                    {row.admin_note ??
                                                                                        '—'}
                                                                                </td>
                                                                                <td className="text-muted-foreground px-3 py-2.5">
                                                                                    {row.created_by
                                                                                        ?.name ?? '—'}
                                                                                </td>
                                                                            </tr>
                                                                        ),
                                                                    )}
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    )}
                                                </div>
                                            </div>
                                        </SettingsSection>
                                    )}

                                    {activeSection === 'referidor' && (
                                        <SettingsSection
                                            title="Referidor"
                                            description="Quién refirió a este usuario en el sistema (referidor directo)."
                                            icon={UserSearch}
                                        >
                                            <p className="text-muted-foreground text-sm leading-relaxed">
                                                Vincula o cambia el referidor directo. Guarda los cambios del perfil
                                                para aplicar.
                                                {referrerChanged ? (
                                                    <span className="text-amber-600 dark:text-amber-500">
                                                        {' '}
                                                        Hay cambios pendientes en el referidor.
                                                    </span>
                                                ) : null}
                                            </p>
                                            {chosenReferrerDisplay ? (
                                                <div className="flex flex-wrap items-center justify-between gap-2 rounded-lg border p-3">
                                                    <div className="min-w-0">
                                                        <p className="font-medium">
                                                            {chosenReferrerDisplay.name}
                                                        </p>
                                                        <p className="text-muted-foreground truncate text-xs">
                                                            {chosenReferrerDisplay.email}
                                                        </p>
                                                    </div>
                                                    <Button
                                                        disabled={form.processing}
                                                        size="sm"
                                                        type="button"
                                                        variant="outline"
                                                        onClick={clearReferrer}
                                                    >
                                                        Quitar referidor
                                                    </Button>
                                                </div>
                                            ) : (
                                                <p className="text-muted-foreground text-sm">
                                                    Sin referidor asignado.
                                                </p>
                                            )}
                                            <div className="grid gap-2">
                                                <Label htmlFor="referrer_search">Buscar referidor</Label>
                                                <div className="relative">
                                                    <Search className="text-muted-foreground absolute top-1/2 left-3 size-4 -translate-y-1/2" />
                                                    <Input
                                                        autoComplete="off"
                                                        className="pl-9"
                                                        disabled={form.processing}
                                                        id="referrer_search"
                                                        placeholder="Correo, nombre o código…"
                                                        value={referrerSearchQuery}
                                                        onChange={(e) =>
                                                            setReferrerSearchQuery(e.target.value)
                                                        }
                                                    />
                                                </div>
                                                <p className="text-muted-foreground text-xs">
                                                    Mínimo 2 caracteres. No puede ser el propio usuario.
                                                </p>
                                                {referrerSuggestions.length > 0 ? (
                                                    <ul
                                                        className="divide-border max-h-52 overflow-auto rounded-md border text-sm"
                                                        role="listbox"
                                                    >
                                                        {referrerSuggestions.map((row) => (
                                                            <li key={row.id}>
                                                                <button
                                                                    className="hover:bg-muted/60 flex w-full flex-col items-start gap-0.5 px-3 py-2.5 text-left transition-colors disabled:opacity-50"
                                                                    disabled={form.processing}
                                                                    type="button"
                                                                    onClick={() => pickReferrer(row)}
                                                                >
                                                                    <span className="font-medium">{row.name}</span>
                                                                    <span className="text-muted-foreground text-xs">
                                                                        {row.email} ·{' '}
                                                                        <span className="font-mono">
                                                                            {row.referral_code}
                                                                        </span>
                                                                    </span>
                                                                </button>
                                                            </li>
                                                        ))}
                                                    </ul>
                                                ) : null}
                                                <InputError message={form.errors.referred_by_user_id} />
                                            </div>
                                        </SettingsSection>
                                    )}

                                    {activeSection === 'referidos_directos' &&
                                    user.can_manage_manual_referrer ? (
                                        <SettingsSection
                                            title="Referidos directos (manual)"
                                            description={`Cada usuario que agregues quedará vinculado como si se hubiera registrado con el código ${user.referral_code} de ${name}. Puedes quitar el vínculo aquí; no recalcula comisiones pasadas.`}
                                            icon={Users}
                                        >
                                    {user.direct_referrals.length === 0 ? (
                                        <p className="text-muted-foreground text-sm">
                                            Nadie está vinculado todavía como referido directo de esta cuenta.
                                        </p>
                                    ) : (
                                        <ul className="divide-border rounded-md border text-sm" role="list">
                                            {user.direct_referrals.map((row) => (
                                                <li
                                                    className="flex flex-wrap items-center justify-between gap-3 px-3 py-3"
                                                    key={row.id}
                                                >
                                                    <div className="min-w-0 flex-1 space-y-1">
                                                        <p className="font-medium">{row.name}</p>
                                                        <p className="text-muted-foreground truncate text-xs">
                                                            {row.email} ·{' '}
                                                            <span className="font-mono">{row.referral_code}</span>
                                                        </p>
                                                        {!row.referral_program_enabled ? (
                                                            <p className="text-xs text-amber-600 dark:text-amber-500">
                                                                Sin programa de referidos activo en su ficha.
                                                            </p>
                                                        ) : null}
                                                    </div>
                                                    <div className="flex shrink-0 flex-wrap gap-2">
                                                        <Button asChild size="sm" variant="outline">
                                                            <Link href={`/admin/usuarios/${row.id}/editar`}>
                                                                Abrir ficha
                                                            </Link>
                                                        </Button>
                                                        <Button
                                                            disabled={referralDetachForm.processing}
                                                            size="sm"
                                                            type="button"
                                                            variant="destructive"
                                                            onClick={() => openDetachReferral(row)}
                                                        >
                                                            Quitar
                                                        </Button>
                                                    </div>
                                                </li>
                                            ))}
                                        </ul>
                                    )}

                                    <div className="grid gap-2 border-t pt-4">
                                        <Label htmlFor="direct_referral_search">
                                            Añadir referido (buscar usuario)
                                        </Label>
                                        <div className="relative">
                                            <Search className="text-muted-foreground absolute top-1/2 left-3 size-4 -translate-y-1/2" />
                                            <Input
                                                autoComplete="off"
                                                className="pl-9"
                                                disabled={form.processing || directReferralAttaching}
                                                id="direct_referral_search"
                                                placeholder="Correo, nombre o código…"
                                                value={directReferralSearchQuery}
                                                onChange={(e) =>
                                                    setDirectReferralSearchQuery(e.target.value)
                                                }
                                            />
                                        </div>
                                        <p className="text-muted-foreground text-xs">
                                            Mínimo 2 caracteres. Ya se excluyen esta cuenta y los referidos ya
                                            vinculados.
                                        </p>
                                        {directReferralSuggestions.length > 0 ? (
                                            <ul
                                                className="divide-border max-h-52 overflow-auto rounded-md border text-sm"
                                                role="listbox"
                                            >
                                                {directReferralSuggestions.map((row) => (
                                                    <li key={row.id}>
                                                        <button
                                                            className="hover:bg-muted/60 flex w-full flex-col items-start gap-0.5 px-3 py-2.5 text-left transition-colors disabled:opacity-50"
                                                            disabled={directReferralAttaching}
                                                            type="button"
                                                            onClick={() => attachDirectReferral(row)}
                                                        >
                                                            <span className="font-medium">{row.name}</span>
                                                            <span className="text-muted-foreground text-xs">
                                                                {row.email} ·{' '}
                                                                <span className="font-mono">
                                                                    {row.referral_code}
                                                                </span>
                                                            </span>
                                                        </button>
                                                    </li>
                                                ))}
                                            </ul>
                                        ) : null}
                                    </div>

                                    <InputError message={firstError(pageErrors?.referred_user_id)} />
                                        </SettingsSection>
                                    ) : null}

                                    {activeSection === 'acceso' && !user.is_admin && (
                                        <SettingsSection
                                            title="Acceso al portal"
                                            description="Suspende el inicio de sesión para este usuario (la sesión activa se cerrará en la siguiente visita protegida)."
                                            icon={Shield}
                                        >
                                            {user.is_admin ? (
                                                <Alert>
                                                    <AlertTitle>Cuentas de administrador</AlertTitle>
                                                    <AlertDescription>
                                                        Esta pantalla no bloquea administradores como medida
                                                        anti-cierre inadvertido del panel.
                                                    </AlertDescription>
                                                </Alert>
                                            ) : null}

                                            {user.can_toggle_access_block ? (
                                                <ToggleRow
                                                    checked={form.data.access_blocked}
                                                    destructive
                                                    disabled={form.processing}
                                                    id="access_blocked"
                                                    onCheckedChange={(v) =>
                                                        form.setData('access_blocked', v)
                                                    }
                                                    title="Bloquear acceso (suspendido)"
                                                    description={`Impide iniciar sesión hasta volver a desmarcar esta casilla aquí y guardar.${
                                                        user.blocked_at
                                                            ? ` Registro desde ${new Intl.DateTimeFormat('es', {
                                                                  dateStyle: 'medium',
                                                                  timeStyle: 'short',
                                                              }).format(new Date(user.blocked_at))}.`
                                                            : ''
                                                    }`}
                                                />
                                            ) : (
                                                <Alert>
                                                    <AlertTitle>No disponible</AlertTitle>
                                                    <AlertDescription>
                                                        {user.is_admin
                                                            ? 'Los administradores no se pueden bloquear desde aquí.'
                                                            : isSelf
                                                              ? 'No puedes usar tu sesión para bloquearte a ti mismo.'
                                                              : 'No puedes aplicar suspensión a este usuario con tu cuenta actual.'}
                                                    </AlertDescription>
                                                </Alert>
                                            )}

                                            <InputError message={form.errors.access_blocked} />
                                        </SettingsSection>
                                    )}
                                </div>

                                {showProfileSaveBar ? (
                                    <div className="border-border bg-background/95 supports-[backdrop-filter]:bg-background/80 sticky bottom-0 z-10 -mx-1 mt-2 flex flex-wrap items-center justify-between gap-3 rounded-lg border px-4 py-3 shadow-sm backdrop-blur sm:-mx-2">
                                        <p className="text-muted-foreground text-sm">
                                            <span className="text-foreground font-medium">
                                                {activeMeta.label}
                                            </span>
                                            {' · '}
                                            {form.isDirty
                                                ? 'Hay cambios sin guardar.'
                                                : 'Todos los cambios están guardados.'}
                                        </p>
                                        <Button
                                            disabled={form.processing || !form.isDirty}
                                            type="submit"
                                        >
                                            {form.processing ? 'Guardando…' : 'Guardar cambios'}
                                        </Button>
                                    </div>
                                ) : null}
                            </form>
                        )}
                    </div>
                </div>
            </div>
        </>
    );
}

AdminUserEdit.layout = {
    breadcrumbs: [
        { title: 'Administración', href: '/admin' },
        { title: 'Usuarios', href: '/admin/usuarios' },
        { title: 'Editar', href: '#' },
    ],
};
