import { Head, Link, usePage } from '@inertiajs/react';
import { HandCoins, Landmark, ListOrdered, Star, Wallet as WalletIcon } from 'lucide-react';
import { useMemo, useState } from 'react';
import {
    AppPage,
    AppPageActions,
    AppPageHeader,
    AppPageTitleBlock,
    AppSectionHeading,
    appCardAccentClass,
} from '@/components/app-page';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
    RequestWithdrawalDialog,
    type WithdrawOption,
} from '@/pages/investments/components/request-withdrawal-dialog';
import type { UserPortfolioInvestment } from '@/pages/investments/types-user-portfolio';
import { formatCurrency } from '@/pages/investments/utils';
import { dashboard } from '@/routes';

type WithdrawalLite = {
    id: number;
    amount_usd: string;
    fee_total_usd?: string;
    net_amount_usd?: string;
    status: string;
    investment_txid: string;
    destination_network: string | null;
    destination_address: string | null;
    destination_label: string | null;
    payout_txid: string | null;
    created_at: string | null;
    processed_at: string | null;
};

type Props = {
    investments: UserPortfolioInvestment[];
    balance_total: string;
    invested_active_total: string;
    withdrawable_total: string;
    withdrawal_fee_percent: string;
    withdrawal_fee_fixed: string;
    min_withdrawal_amount: string;
    referral_balance_total?: string;
    invested_pending_total: string;
    invested_any: boolean;
    wallet_count: number;
    portfolio_withdrawal_pending: boolean;
    wallets: WithdrawOption[];
    withdrawals_pending: WithdrawalLite[];
    withdrawals_recent: WithdrawalLite[];
};

function shortWallet(address: string | null | undefined): string {
    if (!address) return '—';
    if (address.length <= 20) return address;
    return `${address.slice(0, 10)}…${address.slice(-8)}`;
}

export default function BalancesPage({
    investments,
    balance_total,
    invested_active_total,
    withdrawable_total,
    withdrawal_fee_percent,
    withdrawal_fee_fixed,
    min_withdrawal_amount,
    referral_balance_total = '0',
    invested_pending_total,
    invested_any,
    wallet_count,
    portfolio_withdrawal_pending,
    wallets,
    withdrawals_pending,
    withdrawals_recent,
}: Props) {
    const page = usePage<{
        kyc?: {
            investor_portal_unlocked?: boolean;
            require_kyc_for_withdraw?: boolean;
            require_kyc_for_invest?: boolean;
        };
    }>();
    const unlocked = page.props.kyc?.investor_portal_unlocked === true;
    const requireWithdrawKyc = page.props.kyc?.require_kyc_for_withdraw ?? true;
    const requireInvestKyc = page.props.kyc?.require_kyc_for_invest ?? true;
    const kycAllowsWithdrawals = unlocked || !requireWithdrawKyc;
    const kycAllowsInvest = unlocked || !requireInvestKyc;

    const [withdrawOpen, setWithdrawOpen] = useState(false);

    const formattedBalanceTotal = useMemo(
        () => formatCurrency(Number(balance_total)),
        [balance_total],
    );
    const formattedActive = useMemo(
        () => formatCurrency(Number(invested_active_total)),
        [invested_active_total],
    );
    const pendingAwaitsEmail = useMemo(
        () => withdrawals_pending.some((w) => w.status === 'pending_email'),
        [withdrawals_pending],
    );
    const formattedPending = useMemo(
        () => formatCurrency(Number(invested_pending_total)),
        [invested_pending_total],
    );

    const availableConsolidatedBalance = Number(withdrawable_total.replace(/,/g, '') || 0);
    const formattedWithdrawable = useMemo(
        () => formatCurrency(availableConsolidatedBalance),
        [availableConsolidatedBalance],
    );

    const canWithdrawFromPortfolio =
        kycAllowsWithdrawals &&
        wallet_count > 0 &&
        !portfolio_withdrawal_pending &&
        availableConsolidatedBalance > 0.001;

    const canReinvestFromBalance = kycAllowsInvest && availableConsolidatedBalance >= 0.01;

    return (
        <>
            <Head title="Mis balances" />

            <AppPage>
                <AppPageHeader>
                    <AppPageTitleBlock
                        title="Mis balances"
                        description={
                            <>
                                Resumen de tu capital distribuido en inversiones, movimientos y estado de retiros
                                solicitados desde tu <strong className="text-foreground">balance consolidado</strong>.
                            </>
                        }
                    />
                    <AppPageActions>
                        <Button
                            disabled={
                                !kycAllowsWithdrawals ||
                                wallet_count === 0 ||
                                portfolio_withdrawal_pending ||
                                availableConsolidatedBalance < 0.01
                            }
                            type="button"
                            variant="default"
                            onClick={() => setWithdrawOpen(true)}
                        >
                            <HandCoins className="size-4" />
                            Solicitar retiro
                        </Button>
                        <Button asChild variant="outline">
                            <Link href="/balances/movimientos">
                                <ListOrdered />
                                Movimientos
                            </Link>
                        </Button>
                        <Button asChild variant="secondary">
                            <Link href="/balances/billeteras">
                                <WalletIcon />
                                Mis billeteras
                                {wallet_count > 0 ? (
                                    <span className="ml-1 rounded bg-background px-1.5 py-px text-xs">
                                        {wallet_count}
                                    </span>
                                ) : null}
                            </Link>
                        </Button>
                    </AppPageActions>
                </AppPageHeader>

                {requireWithdrawKyc && !unlocked ? (
                    <div className="rounded-xl border border-amber-500/40 bg-amber-500/15 px-4 py-3 text-sm">
                        Cuando tu{' '}
                        <Link className="font-medium underline" href="/verificacion-kyc">
                            verificación de identidad
                        </Link>{' '}
                        esté aprobada podrás solicitar retiros de capital.
                    </div>
                ) : null}

                {pendingAwaitsEmail ? (
                    <div className="rounded-xl border border-amber-500/40 bg-amber-500/15 px-4 py-3 text-sm">
                        Revisa tu correo: debes <strong className="text-foreground">confirmar el retiro</strong> desde el
                        enlace que te enviamos antes de que el equipo pueda procesarlo.
                    </div>
                ) : null}

                {!pendingAwaitsEmail && portfolio_withdrawal_pending ? (
                    <div className="rounded-xl border border-amber-500/40 bg-amber-500/15 px-4 py-3 text-sm">
                        Tienes una solicitud de retiro pendiente de revisión. Cuando esté lista podrás enviar una nueva.
                    </div>
                ) : null}

                {wallet_count === 0 ? (
                    <div className="rounded-xl border border-amber-500/40 bg-amber-500/15 px-4 py-3 text-sm">
                        Antes de solicitar retiros necesitas registrar al menos una dirección externa en{' '}
                        <Link className="font-medium underline" href="/balances/billeteras">
                            Mis billeteras
                        </Link>
                        .
                    </div>
                ) : null}

                <Card className={appCardAccentClass}>
                    <CardHeader className="pb-3">
                        <CardTitle className="flex items-center gap-2 text-xl">
                            <Landmark className="size-5" />
                            Resumen
                        </CardTitle>
                    </CardHeader>
                    <CardContent className="grid gap-4 sm:grid-cols-3">
                        <div className="rounded-xl bg-background p-4 text-center">
                            <p className="text-sm text-muted-foreground">Balance total</p>
                            <p className="mt-1 text-lg font-semibold tabular-nums text-foreground">
                                ${formattedBalanceTotal}
                            </p>
                            <p className="mt-2 text-xs leading-relaxed text-muted-foreground">
                                Inversiones: ${formattedActive} | disponible para retiro: $
                                {formattedWithdrawable}
                            </p>
                        </div>
                        <div className="rounded-xl bg-background p-4 text-center">
                            <p className="text-sm text-muted-foreground">
                                Pendiente de confirmación
                            </p>
                            <p className="mt-1 text-lg font-semibold tabular-nums text-primary">
                                {invested_any ? `$${formattedPending}` : '$0'}
                            </p>
                        </div>
                        <div className="rounded-xl bg-background p-4 text-center">
                            <p className="text-sm text-muted-foreground">
                                Disponible para solicitar retiro (bruto)
                            </p>
                            <p className="mt-1 text-lg font-semibold tabular-nums">
                                {availableConsolidatedBalance > 0
                                    ? `$${formatCurrency(availableConsolidatedBalance)}`
                                    : '$0'}
                            </p>
                            {Number(referral_balance_total) > 0 ? (
                                <p className="mt-1 text-xs text-muted-foreground">
                                    Incluye comisiones de referidos acreditadas a tu saldo retirable.
                                </p>
                            ) : null}
                            <div className="mt-3 flex flex-wrap justify-center gap-2">
                                {canReinvestFromBalance ? (
                                    <Button
                                        asChild
                                        className="gap-2 border border-violet-400/60 bg-violet-600 text-white shadow-md hover:bg-violet-700 dark:bg-violet-600 dark:hover:bg-violet-500"
                                        size="sm"
                                    >
                                        <Link href="/invertir?reinvertir=1">
                                            <Star className="size-4 fill-amber-300 text-amber-200 drop-shadow-sm" />
                                            Reinvertir
                                        </Link>
                                    </Button>
                                ) : (
                                    <Button
                                        className="gap-2 border border-violet-400/40 bg-violet-600/50 text-white shadow-sm dark:bg-violet-900/40"
                                        disabled
                                        size="sm"
                                        title={
                                            !kycAllowsInvest
                                                ? 'Completa la verificación requerida para invertir.'
                                                : availableConsolidatedBalance < 0.01
                                                  ? 'Necesitas saldo retirable disponible para reinvertir.'
                                                  : undefined
                                        }
                                        type="button"
                                    >
                                        <Star className="size-4 opacity-70" />
                                        Reinvertir
                                    </Button>
                                )}
                            </div>
                        </div>
                    </CardContent>
                </Card>

                <div className="space-y-3">
                    <AppSectionHeading>Mis retiros</AppSectionHeading>
                    <p className="text-sm text-muted-foreground">
                        Lista de tus retiros pendientes y procesados.
                    </p>

                    <Card className={appCardAccentClass}>
                        <CardHeader className="pb-2">
                            <CardTitle className="text-base">Pendientes</CardTitle>
                        </CardHeader>
                        <CardContent className="overflow-x-auto p-0 pb-4">
                            {withdrawals_pending.length === 0 ? (
                                <p className="px-4 pb-4 text-center text-sm text-muted-foreground">
                                    No tienes solicitudes de retiro en cola.
                                </p>
                            ) : (
                                <table className="w-full min-w-[760px] text-left text-sm">
                                    <thead>
                                        <tr className="border-b bg-muted/40 text-muted-foreground">
                                            <th className="px-4 py-2 font-medium">Origen del retiro</th>
                                            <th className="px-4 py-2 font-medium tabular-nums">Monto</th>
                                            <th className="px-4 py-2 font-medium">Destino</th>
                                            <th className="px-4 py-2 font-medium">Alta</th>
                                            <th className="px-4 py-2 font-medium text-right">
                                                Estado
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-border">
                                        {withdrawals_pending.map((w) => (
                                            <tr key={w.id}>
                                                <td className="px-4 py-2 text-xs">{w.investment_txid}</td>
                                                <td className="px-4 py-2 tabular-nums font-semibold text-primary">
                                                    {w.amount_usd} US$
                                                </td>
                                                <td className="px-4 py-2 text-xs">
                                                    <div>{w.destination_network ?? '—'}</div>
                                                    <div className="text-muted-foreground" title={w.destination_address ?? ''}>
                                                        {w.destination_label
                                                            ? `${w.destination_label} · `
                                                            : null}
                                                        {shortWallet(w.destination_address)}
                                                    </div>
                                                </td>
                                                <td className="whitespace-nowrap px-4 py-2 text-xs text-muted-foreground">
                                                    {w.created_at
                                                        ? new Date(w.created_at).toLocaleString('es', {
                                                              dateStyle: 'short',
                                                              timeStyle: 'short',
                                                          })
                                                        : '—'}
                                                </td>
                                                <td className="px-4 py-2 text-right">
                                                    <Badge variant="outline">
                                                        {w.status === 'pending_email'
                                                            ? 'Correo pendiente'
                                                            : 'En revisión'}
                                                    </Badge>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            )}
                        </CardContent>
                    </Card>

                    <Card>
                        <CardHeader className="pb-2">
                            <CardTitle className="text-base">Últimas resoluciones</CardTitle>
                        </CardHeader>
                        <CardContent className="overflow-x-auto p-0 pb-4">
                            {withdrawals_recent.length === 0 ? (
                                <p className="px-4 pb-4 text-center text-sm text-muted-foreground">
                                    Aún no hay retiros procesados registrados aquí.
                                </p>
                            ) : (
                                <table className="w-full min-w-[760px] text-left text-sm">
                                    <thead>
                                        <tr className="border-b bg-muted/40 text-muted-foreground">
                                            <th className="px-4 py-2 font-medium">Estado</th>
                                            <th className="px-4 py-2 font-medium">Origen</th>
                                            <th className="px-4 py-2 font-medium tabular-nums">Monto</th>
                                            <th className="px-4 py-2 font-medium">TX payout</th>
                                            <th className="px-4 py-2 font-medium">Fecha</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-border">
                                        {withdrawals_recent.map((w) => (
                                            <tr key={`r-${w.id}`}>
                                                <td className="px-4 py-2">
                                                    <Badge
                                                        variant={
                                                            w.status === 'approved'
                                                                ? 'secondary'
                                                                : 'outline'
                                                        }
                                                    >
                                                        {w.status === 'approved'
                                                            ? 'Aprobado'
                                                            : 'Rechazado'}
                                                    </Badge>
                                                </td>
                                                <td className="px-4 py-2 text-xs">{w.investment_txid}</td>
                                                <td className="px-4 py-2 tabular-nums">{w.amount_usd} US$</td>
                                                <td className="max-w-[200px] overflow-hidden text-ellipsis px-4 py-2 font-mono text-xs">
                                                    {w.payout_txid ? (
                                                        <span title={w.payout_txid}>{w.payout_txid}</span>
                                                    ) : (
                                                        <span className="text-muted-foreground">—</span>
                                                    )}
                                                </td>
                                                <td className="whitespace-nowrap px-4 py-2 text-xs text-muted-foreground">
                                                    {w.processed_at
                                                        ? new Date(w.processed_at).toLocaleString('es', {
                                                              dateStyle: 'short',
                                                              timeStyle: 'short',
                                                          })
                                                        : '—'}
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            )}
                        </CardContent>
                    </Card>
                </div>
            </AppPage>

            <RequestWithdrawalDialog
                capitalAvailableUsd={withdrawable_total}
                minWithdrawalUsd={min_withdrawal_amount}
                withdrawalFeePercent={withdrawal_fee_percent}
                withdrawalFeeFixed={withdrawal_fee_fixed}
                open={withdrawOpen}
                wallets={wallets ?? []}
                onClose={() => setWithdrawOpen(false)}
            />
        </>
    );
}

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