import { Head, Link } from '@inertiajs/react';
import { ArrowLeft, ChevronDown, ChevronRight, Users } from 'lucide-react';
import { Fragment, useState } from 'react';
import { Badge } from '@/components/ui/badge';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { cn } from '@/lib/utils';

type ReferralLine = {
    id: number;
    level: number | null;
    type_label: string;
    beneficiary_name: string;
    beneficiary_email: string | null;
    amount_usd: string;
    percent: string | null;
};

type AccrualLine = {
    id: number;
    type: string;
    type_label: string;
    accrual_on: string | null;
    amount_usd: string;
    balance_after_usd: string | null;
    applied_percent_label: string | null;
    gain_period_start: string | null;
    gain_period_end: string | null;
    period_label: string | null;
    investment_month_index: number | null;
    referral_paid: boolean;
    referral_total_usd: string;
    referrals: ReferralLine[];
};

type Props = {
    investment: {
        id: number;
        txid: string;
        status: string;
        amount: string;
        capital_balance: string;
        duration_months: number;
        months_credited: number;
        monthly_return_snapshot: string;
        investor_name: string;
        investor_email: string | null;
    };
    summary: {
        accrual_count: number;
        total_gain_usd: string;
        total_referral_usd: string;
    };
    lines: AccrualLine[];
};

function formatDate(iso: string | null): string {
    if (!iso) {
        return '—';
    }
    try {
        return new Intl.DateTimeFormat('es', { dateStyle: 'medium' }).format(new Date(iso));
    } catch {
        return iso;
    }
}

function statusLabel(status: string): string {
    if (status === 'active') {
        return 'Activa';
    }
    if (status === 'completed') {
        return 'Finalizada';
    }
    return status;
}

export default function InvestmentAccruals({ investment, summary, lines }: Props) {
    const backTab = investment.status === 'completed' ? 'completed' : 'active';
    const backHref = `/admin/inversiones?tab=${backTab}`;
    const [expandedId, setExpandedId] = useState<number | null>(null);

    function toggleLine(id: number) {
        setExpandedId((current) => (current === id ? null : id));
    }

    return (
        <>
            <Head title={`Acreditaciones — ${investment.txid}`} />

            <div className="mx-auto max-w-6xl space-y-6">
                <Link
                    className="text-muted-foreground hover:text-foreground inline-flex items-center gap-2 text-sm"
                    href={backHref}
                >
                    <ArrowLeft className="size-4" />
                    Volver a inversiones
                </Link>

                <div className="space-y-2">
                    <div className="flex flex-wrap items-center gap-2">
                        <h1 className="text-2xl font-bold tracking-tight sm:text-3xl">
                            Acreditaciones de la inversión
                        </h1>
                        <Badge variant="outline">{statusLabel(investment.status)}</Badge>
                    </div>
                    <p className="text-muted-foreground text-sm">
                        {investment.investor_name}
                        {investment.investor_email ? ` · ${investment.investor_email}` : ''}
                    </p>
                    <p className="text-muted-foreground font-mono text-xs break-all">
                        TXID: {investment.txid}
                    </p>
                </div>

                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Principal (US$)</CardDescription>
                            <CardTitle className="text-2xl tabular-nums">{investment.amount}</CardTitle>
                        </CardHeader>
                    </Card>
                    <Card className="border-primary/35 bg-primary/10">
                        <CardHeader className="pb-2">
                            <CardDescription>Capital vigente (US$)</CardDescription>
                            <CardTitle className="text-primary text-2xl tabular-nums">
                                {investment.capital_balance}
                            </CardTitle>
                        </CardHeader>
                    </Card>
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Acreditaciones</CardDescription>
                            <CardTitle className="text-2xl tabular-nums">
                                {summary.accrual_count}
                            </CardTitle>
                        </CardHeader>
                    </Card>
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Total ganancias (US$)</CardDescription>
                            <CardTitle className="text-primary text-2xl tabular-nums">
                                {summary.total_gain_usd}
                            </CardTitle>
                        </CardHeader>
                    </Card>
                    <Card>
                        <CardHeader className="pb-2">
                            <CardDescription>Referidos pagados (US$)</CardDescription>
                            <CardTitle className="text-2xl tabular-nums">
                                {summary.total_referral_usd}
                            </CardTitle>
                        </CardHeader>
                    </Card>
                </div>

                <Card>
                    <CardHeader>
                        <CardTitle>Detalle por movimiento</CardTitle>
                        <CardDescription>
                            Plan {investment.monthly_return_snapshot}% mensual · acreditaciones{' '}
                            {investment.months_credited}/{investment.duration_months}. Pulsa una
                            fila para ver comisiones de referidos generadas por esa acreditación.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="overflow-x-auto p-0">
                        {lines.length === 0 ? (
                            <p className="text-muted-foreground p-10 text-center text-sm">
                                Esta inversión aún no tiene acreditaciones de rendimiento.
                            </p>
                        ) : (
                            <table className="w-full min-w-[920px] text-left text-sm">
                                <thead>
                                    <tr className="bg-muted/40 text-muted-foreground border-b">
                                        <th className="w-8 px-2 py-3" aria-hidden />
                                        <th className="px-4 py-3 font-medium">Entrega</th>
                                        <th className="px-4 py-3 font-medium">Tipo</th>
                                        <th className="px-4 py-3 font-medium">Período</th>
                                        <th className="px-4 py-3 font-medium tabular-nums">% aplicado</th>
                                        <th className="px-4 py-3 text-right font-medium tabular-nums">
                                            Monto (US$)
                                        </th>
                                        <th className="px-4 py-3 text-right font-medium tabular-nums">
                                            Capital después
                                        </th>
                                        <th className="px-4 py-3 font-medium">Referidos</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y">
                                    {lines.map((line) => {
                                        const expanded = expandedId === line.id;
                                        const canExpand = line.referral_paid;

                                        return (
                                            <Fragment key={line.id}>
                                                <tr
                                                    className={cn(
                                                        canExpand && 'hover:bg-muted/20 cursor-pointer',
                                                        expanded && 'bg-muted/10',
                                                    )}
                                                    onClick={() => {
                                                        if (canExpand) {
                                                            toggleLine(line.id);
                                                        }
                                                    }}
                                                >
                                                    <td className="px-2 py-3 text-muted-foreground">
                                                        {canExpand ? (
                                                            expanded ? (
                                                                <ChevronDown className="size-4" />
                                                            ) : (
                                                                <ChevronRight className="size-4" />
                                                            )
                                                        ) : null}
                                                    </td>
                                                    <td className="px-4 py-3 whitespace-nowrap">
                                                        {formatDate(line.accrual_on)}
                                                    </td>
                                                    <td className="px-4 py-3">{line.type_label}</td>
                                                    <td className="text-muted-foreground px-4 py-3 text-xs whitespace-nowrap">
                                                        {line.period_label
                                                            ? line.period_label
                                                            : line.gain_period_start &&
                                                                line.gain_period_end
                                                              ? `${formatDate(line.gain_period_start)} – ${formatDate(line.gain_period_end)}`
                                                              : line.investment_month_index !==
                                                                  null
                                                                ? `Mes ${line.investment_month_index}`
                                                                : '—'}
                                                    </td>
                                                    <td className="px-4 py-3 text-xs tabular-nums">
                                                        {line.applied_percent_label ?? '—'}
                                                    </td>
                                                    <td className="px-4 py-3 text-right font-medium text-primary tabular-nums">
                                                        {line.amount_usd}
                                                    </td>
                                                    <td className="text-muted-foreground px-4 py-3 text-right tabular-nums">
                                                        {line.balance_after_usd ?? '—'}
                                                    </td>
                                                    <td className="px-4 py-3">
                                                        {line.referral_paid ? (
                                                            <Badge
                                                                className="tabular-nums"
                                                                variant="secondary"
                                                            >
                                                                <Users className="size-3" />
                                                                {line.referral_total_usd} US$
                                                            </Badge>
                                                        ) : (
                                                            <span className="text-muted-foreground text-xs">
                                                                No
                                                            </span>
                                                        )}
                                                    </td>
                                                </tr>
                                                {expanded && line.referrals.length > 0 ? (
                                                    <tr className="bg-muted/15">
                                                        <td colSpan={8} className="px-4 py-4">
                                                            <p className="text-muted-foreground mb-3 text-xs font-medium tracking-wide uppercase">
                                                                Comisiones de referidos por esta
                                                                acreditación
                                                            </p>
                                                            <div className="overflow-x-auto rounded-lg border">
                                                                <table className="w-full min-w-[520px] text-left text-sm">
                                                                    <thead>
                                                                        <tr className="bg-muted/30 text-muted-foreground border-b text-xs">
                                                                            <th className="px-3 py-2 font-medium">
                                                                                Beneficiario
                                                                            </th>
                                                                            <th className="px-3 py-2 font-medium">
                                                                                Nivel
                                                                            </th>
                                                                            <th className="px-3 py-2 text-right font-medium tabular-nums">
                                                                                % sobre ganancia
                                                                            </th>
                                                                            <th className="px-3 py-2 text-right font-medium tabular-nums">
                                                                                Monto (US$)
                                                                            </th>
                                                                        </tr>
                                                                    </thead>
                                                                    <tbody className="divide-y">
                                                                        {line.referrals.map((ref) => (
                                                                            <tr key={ref.id}>
                                                                                <td className="px-3 py-2">
                                                                                    <div className="font-medium">
                                                                                        {
                                                                                            ref.beneficiary_name
                                                                                        }
                                                                                    </div>
                                                                                    {ref.beneficiary_email ? (
                                                                                        <div className="text-muted-foreground text-xs">
                                                                                            {
                                                                                                ref.beneficiary_email
                                                                                            }
                                                                                        </div>
                                                                                    ) : null}
                                                                                </td>
                                                                                <td className="px-3 py-2">
                                                                                    <Badge
                                                                                        className="text-xs font-normal"
                                                                                        variant="outline"
                                                                                    >
                                                                                        {ref.type_label}
                                                                                    </Badge>
                                                                                </td>
                                                                                <td className="text-muted-foreground px-3 py-2 text-right text-xs tabular-nums">
                                                                                    {ref.percent
                                                                                        ? `${ref.percent}%`
                                                                                        : '—'}
                                                                                </td>
                                                                                <td className="px-3 py-2 text-right font-medium tabular-nums">
                                                                                    {ref.amount_usd}
                                                                                </td>
                                                                            </tr>
                                                                        ))}
                                                                    </tbody>
                                                                </table>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                ) : null}
                                            </Fragment>
                                        );
                                    })}
                                </tbody>
                            </table>
                        )}
                    </CardContent>
                </Card>
            </div>
        </>
    );
}

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