import type { ReactNode } from 'react';
import { Head, Link, usePage } from '@inertiajs/react';
import {
    ArrowRight,
    Coins,
    Landmark,
    LayoutList,
    ListOrdered,
    PieChart,
    Plus,
    Settings,
    Shield,
    AlertTriangle,
    Wallet as WalletIcon,
} from 'lucide-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, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { formatCurrency } from '@/pages/investments/utils';
import { dashboard } from '@/routes';

type LedgerPreviewRow = {
    id: number;
    type: string;
    amount_usd: string;
    investment_txid: string;
    created_at: string | null;
};

type PageProps = {
    invested_active_total?: string;
    invested_pending_total?: string;
    invested_any?: boolean;
    investments_count?: number;
    active_investments_count?: number;
    pending_investments_count?: number;
    wallet_count?: number;
    portfolio_withdrawal_pending?: boolean;
    recent_transactions?: LedgerPreviewRow[];
};

function ledgerTypeLabel(code: string): string {
    const map: Record<string, string> = {
        deposit: 'Depósito',
        monthly_gain: 'Acreditación',
        withdrawal: 'Retiro',
        admin_adjustment: 'Ajuste administrativo',
        admin_adjustment_reversal: 'Reversión de ajuste',
        referral_direct_bonus: 'Bono referido directo',
        referral_indirect_bonus: 'Bono referido indirecto',
    };

    return map[code] ?? code;
}

function ledgerBadgeVariant(
    code: string,
): 'default' | 'secondary' | 'outline' {
    if (code === 'monthly_gain') return 'secondary';
    if (code === 'withdrawal') return 'outline';
    if (code.startsWith('referral_')) return 'secondary';

    return 'default';
}

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

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

export default function Dashboard() {
    const pageProps = usePage().props as PageProps;
    const investedAny = Boolean(pageProps.invested_any);
    const investmentsCount = pageProps.investments_count ?? 0;
    const activeCount = pageProps.active_investments_count ?? 0;
    const pendingInvCount = pageProps.pending_investments_count ?? 0;
    const walletCount = pageProps.wallet_count ?? 0;
    const withdrawalPending = pageProps.portfolio_withdrawal_pending === true;
    const recent = pageProps.recent_transactions ?? [];
    const investedActiveTotal = Number(pageProps.invested_active_total ?? '0');
    const investedPendingTotal = Number(pageProps.invested_pending_total ?? '0');

    const authUser = usePage().props.auth?.user;
    const isAdmin = authUser?.is_admin === true;

    const firstName =
        typeof authUser?.first_name === 'string' && authUser.first_name.trim().length > 0
            ? authUser.first_name.trim()
            : null;

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

            <AppPage>
                <AppPageHeader>
                    <AppPageTitleBlock
                        title={firstName ? `Hola, ${firstName}` : 'Bienvenido'}
                        description="Estado de tus inversiones, capital consolidado y accesos rápidos para operar desde tu cuenta."
                    />
                    <AppPageActions>
                        <Button asChild>
                            <Link href="/invertir">
                                <Plus className="size-4" />
                                Nueva inversión
                            </Link>
                        </Button>
                        {isAdmin ? (
                            <>
                                <Button variant="outline" asChild size="sm">
                                    <Link href="/admin">
                                        <Shield className="size-4" />
                                        Admin
                                    </Link>
                                </Button>
                                <Button variant="outline" asChild size="sm">
                                    <Link href="/settings/profile">
                                        <Settings className="size-4" />
                                        Cuenta
                                    </Link>
                                </Button>
                            </>
                        ) : (
                            <Button variant="outline" asChild size="sm">
                                <Link href="/settings/profile">
                                    <Settings className="size-4" />
                                    Cuenta
                                </Link>
                            </Button>
                        )}
                    </AppPageActions>
                </AppPageHeader>

                {withdrawalPending ? (
                    <Card className="border-primary/60 bg-primary/10">
                        <CardContent className="flex gap-4 p-5 sm:items-start">
                            <div className="mt-0.5 shrink-0 text-primary">
                                <AlertTriangle className="size-6" />
                            </div>
                            <div>
                                <p className="font-semibold">Retiro en revisión</p>
                                <p className="mt-1 text-sm text-muted-foreground">
                                    Tienes una solicitud pendiente sobre tu balance consolidado. El equipo la
                                    resolverá antes de poder enviar una nueva en{' '}
                                    <Link className="font-medium underline" href="/balances">
                                        Mis balances
                                    </Link>
                                    .
                                </p>
                            </div>
                        </CardContent>
                    </Card>
                ) : null}

                <Card className={appCardAccentClass}>
                    <CardContent className="space-y-6 p-6">
                        <h2 className="flex items-center gap-2 text-xl font-bold tracking-tight">
                            <PieChart className="size-5" />
                            Resumen financiero
                        </h2>
                        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
                            <MiniStat label="Capital activo" emphasize value={formatCurrency(investedActiveTotal)} />
                            <MiniStat
                                label="Pendiente de confirmar"
                                value={formatCurrency(investedPendingTotal)}
                                valueClass={pendingInvCount > 0 ? 'text-primary' : undefined}
                            />
                            <MiniStat label="Planes activos" value={String(activeCount)} />
                            <MiniStat
                                hint={walletCount > 0 ? undefined : 'Añade una para retiros'}
                                label="Billeteras registradas"
                                value={String(walletCount)}
                                valueClass={
                                    walletCount === 0 && investedAny ? 'text-primary' : undefined
                                }
                            />
                        </div>
                    </CardContent>
                </Card>

                <section aria-labelledby="quick-actions-heading">
                    <AppSectionHeading id="quick-actions-heading" className="mb-4">
                        Accesos rápidos
                    </AppSectionHeading>
                    <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                        <DashboardQuickLink
                            description="Capital total, solicitar retiros y estado de tus solicitudes."
                            href="/balances"
                            icon={<Landmark className="size-6 text-primary" />}
                            title="Mis balances"
                        />
                        <DashboardQuickLink
                            description={`${investmentsCount} ${investmentsCount === 1 ? 'registro' : 'registros'} por plan pactado.`}
                            href="/mis-inversiones"
                            icon={<LayoutList className="size-6 text-primary" />}
                            title="Mis inversiones"
                        />
                        <DashboardQuickLink
                            description="Depósitos, acreditaciones y retiros en un solo libro."
                            href="/balances/movimientos"
                            icon={<ListOrdered className="size-6 text-primary" />}
                            title="Movimientos"
                        />
                        <DashboardQuickLink
                            description="Gestiona tus direcciones para recibir USDT cuando retires."
                            href="/balances/billeteras"
                            icon={<WalletIcon className="size-6 text-primary" />}
                            title="Mis billeteras"
                        />
                    </div>
                </section>

                {!investedAny ? (
                    <Card>
                        <CardContent className="flex flex-col items-center justify-center gap-5 px-6 py-12 text-center">
                            <TrendingBadge />
                            <div>
                                <h2 className="text-xl font-semibold">Tu primer paso empieza aquí</h2>
                                <p className="mt-2 max-w-md text-muted-foreground">
                                    Aún no hay inversiones vinculadas. Elige importe y plazo, envía tu depósito y el
                                    equipo confirmará cuando la transacción figure en cadena.
                                </p>
                            </div>
                            <Button asChild size="lg">
                                <Link href="/invertir">
                                    <Coins className="size-4" />
                                    Comenzar a invertir
                                </Link>
                            </Button>
                        </CardContent>
                    </Card>
                ) : (
                    <Card className="overflow-hidden">
                        <CardHeader className="flex-row flex-wrap items-center justify-between gap-2 pb-4">
                            <CardTitle className="text-xl">Actividad reciente</CardTitle>
                            <Button variant="outline" size="sm" asChild>
                                <Link href="/balances/movimientos">
                                    Ver todos
                                    <ArrowRight className="size-4" />
                                </Link>
                            </Button>
                        </CardHeader>
                        <CardContent className="overflow-x-auto p-0 pb-px">
                            {recent.length === 0 ? (
                                <p className="p-10 text-center text-sm text-muted-foreground">
                                    Cuando haya cupos mensuales, depósitos o retiros, aparecerán los últimos
                                    movimientos aquí.
                                </p>
                            ) : (
                                <table className="w-full min-w-[620px] text-left text-sm">
                                    <thead>
                                        <tr className="border-b bg-muted/40 text-muted-foreground">
                                            <th className="px-4 py-3 font-medium">Tipo</th>
                                            <th className="px-4 py-3 font-medium tabular-nums">Monto</th>
                                            <th className="px-4 py-3 font-medium">Inversión (TX)</th>
                                            <th className="px-4 py-3 font-medium">Fecha</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y">
                                        {recent.map((row) => (
                                            <tr key={row.id}>
                                                <td className="px-4 py-3">
                                                    <Badge variant={ledgerBadgeVariant(row.type)}>
                                                        {ledgerTypeLabel(row.type)}
                                                    </Badge>
                                                </td>
                                                <td className="px-4 py-3 tabular-nums font-medium">
                                                    {row.amount_usd} US$
                                                </td>
                                                <td className="px-4 py-3 font-mono text-xs">{row.investment_txid}</td>
                                                <td className="px-4 py-3 text-muted-foreground whitespace-nowrap">
                                                    {formatShortDatetime(row.created_at)}
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            )}
                        </CardContent>
                        {recent.length > 0 ? (
                            <CardFooter className="border-t bg-muted/20 py-4 text-xs text-muted-foreground">
                                Resumen consolidado de todas tus inversiones activas. Los retiros aplican desde el
                                capital vigente distribuido en tus registros según orden de libro.
                            </CardFooter>
                        ) : null}
                    </Card>
                )}

                {isAdmin ? (
                    <Card className="border-muted">
                        <CardContent className="flex flex-col gap-4 py-6 sm:flex-row sm:items-center sm:justify-between">
                            <div className="space-y-1">
                                <h2 className="flex items-center gap-2 text-lg font-semibold">
                                    <Shield className="size-5 text-primary" />
                                    Panel de administración
                                </h2>
                                <p className="text-sm text-muted-foreground">
                                    Parámetros, balances, solicitudes de retiro y más están agrupados con pestañas
                                    dentro del panel.
                                </p>
                            </div>
                            <Button variant="secondary" asChild className="shrink-0">
                                <Link href="/admin">
                                    Abrir administración
                                    <ArrowRight className="size-4" />
                                </Link>
                            </Button>
                        </CardContent>
                    </Card>
                ) : null}
            </AppPage>
        </>
    );
}

function MiniStat({
    label,
    value,
    hint,
    emphasize,
    valueClass,
}: {
    label: string;
    value: string;
    hint?: string;
    emphasize?: boolean;
    valueClass?: string;
}) {
    return (
        <div className="rounded-xl bg-background p-4 text-center shadow-sm">
            <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{label}</p>
            <p
                className={`mt-2 tabular-nums text-lg font-semibold sm:text-xl ${
                    emphasize ? 'text-primary' : valueClass ?? 'text-foreground'
                }`}
            >
                {value}
            </p>
            {hint ? (
                <p className="mt-1 text-xs text-muted-foreground">{hint}</p>
            ) : null}
        </div>
    );
}

function DashboardQuickLink({
    href,
    title,
    description,
    icon,
}: {
    href: string;
    title: string;
    description: string;
    icon: ReactNode;
}) {
    return (
        <Link
            className="group flex rounded-xl border border-border bg-card shadow-sm outline-none ring-primary/60 transition-colors hover:bg-muted/30 focus-visible:ring-2"
            href={href}
            prefetch
        >
            <div className="flex flex-1 flex-col gap-2 p-5">
                <div className="flex items-start justify-between gap-3">
                    <div className="rounded-lg bg-primary/15 p-2">{icon}</div>
                    <ArrowRight className="mt-1 size-4 shrink-0 text-muted-foreground transition-transform group-hover:translate-x-0.5 group-hover:text-primary" />
                </div>
                <span className="font-semibold leading-tight">{title}</span>
                <span className="text-sm leading-snug text-muted-foreground">{description}</span>
            </div>
        </Link>
    );
}

function TrendingBadge() {
    return (
        <div className="flex size-14 items-center justify-center rounded-xl bg-primary/20 text-primary">
            <PieChart className="size-7" aria-hidden />
        </div>
    );
}

Dashboard.layout = {
    breadcrumbs: [
        {
            title: 'Inicio',
            href: dashboard(),
        },
    ],
};
