import { Head, Link } from '@inertiajs/react';
import { ArrowLeft } from 'lucide-react';
import {
    AppBackLinkRow,
    AppPage,
    AppPageHeader,
    AppPageTitleBlock,
} from '@/components/app-page';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { InertiaPaginatorFooter } from '@/components/inertia-paginator-footer';
import { dashboard } from '@/routes';
import { formatCurrency } from '@/pages/investments/utils';

export type LedgerRow = {
    id: number;
    type: 'deposit' | 'withdrawal' | 'monthly_gain' | 'daily_gain' | 'period_accrual';
    amount_usd: string;
    balance_after_usd: string;
    applied_percent: string | null;
    reference_month: string | null | undefined;
    investment_month_index: number | null;
    accrual_on: string | null;
    gain_period_start: string | null;
    gain_period_end: string | null;
    created_at: string | null;
};

type PaginatedLedger = {
    data: LedgerRow[];
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    from: number | null;
    to: number | null;
    prev_page_url: string | null;
    next_page_url: string | null;
};

type Props = {
    investment: {
        id: number;
        txid: string;
        status: string;
        principal_usd: string;
        current_capital_usd: string;
    };
    transactions: PaginatedLedger;
};

const typeLabels: Record<LedgerRow['type'], string> = {
    deposit: 'Depósito (confirmación)',
    withdrawal: 'Retiro',
    monthly_gain: 'Ganancia acreditada (hist. mensual)',
    daily_gain: 'Ganancia acreditada (diaria)',
    period_accrual: 'Ganancia acreditada (período mensual)',
};

export default function InvestmentTransactions({ investment, transactions }: Props) {
    return (
        <>
            <Head title="Movimientos de la inversión" />

            <AppPage>
                <AppBackLinkRow>
                    <Button asChild variant="ghost" size="sm" className="w-fit">
                        <Link href="/mis-inversiones">
                            <ArrowLeft className="size-4" />
                            Mis inversiones
                        </Link>
                    </Button>
                </AppBackLinkRow>

                <AppPageHeader>
                    <AppPageTitleBlock
                        title="Movimientos"
                        description="Depósitos, retiros y ganancias aplicadas sobre el capital de esta inversión."
                        descriptionClassName="text-sm"
                    />
                </AppPageHeader>

                <Card>
                    <CardHeader>
                        <div className="flex flex-wrap items-start justify-between gap-3">
                            <div>
                                <CardTitle>Resumen</CardTitle>
                                <CardDescription className="font-mono text-xs mt-2">
                                    TXID: {investment.txid}
                                </CardDescription>
                            </div>
                            <Badge variant="outline">{investment.status}</Badge>
                        </div>
                    </CardHeader>
                    <CardContent className="grid gap-4 sm:grid-cols-2">
                        <div className="rounded-lg border bg-muted/30 p-4">
                            <p className="text-xs uppercase text-muted-foreground">
                                Principal ingresado
                            </p>
                            <p className="mt-1 text-xl font-semibold tabular-nums">
                                {formatCurrency(Number(investment.principal_usd))}
                            </p>
                        </div>
                        <div className="rounded-lg border bg-primary/10 p-4">
                            <p className="text-xs uppercase text-muted-foreground">
                                Capital vigente
                            </p>
                            <p className="mt-1 text-xl font-semibold tabular-nums text-primary">
                                {formatCurrency(Number(investment.current_capital_usd))}
                            </p>
                        </div>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader>
                        <CardTitle>Listado cronológico</CardTitle>
                        <CardDescription>
                            Orden descendente por registro más reciente
                            {transactions.total > 0 ? (
                                <>
                                    {' '}
                                    (
                                    <span className="tabular-nums">{transactions.total}</span>{' '}
                                    registros).
                                </>
                            ) : null}
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-0 overflow-x-auto p-0">
                        {transactions.total === 0 ? (
                            <p className="p-8 text-center text-sm text-muted-foreground">
                                Sin movimientos todavía.
                            </p>
                        ) : (
                            <>
                                <table className="w-full min-w-[640px] text-left text-sm">
                                    <thead>
                                        <tr className="border-b bg-muted/40 text-muted-foreground">
                                            <th className="px-4 py-3 font-medium">
                                                Fecha
                                            </th>
                                            <th className="px-4 py-3 font-medium">
                                                Concepto
                                            </th>
                                            <th className="px-4 py-3 font-medium tabular-nums">
                                                Monto
                                            </th>
                                            <th className="px-4 py-3 font-medium tabular-nums">
                                                Saldo tras mov.
                                            </th>
                                            <th className="px-4 py-3 text-xs font-medium">
                                                Detalle %
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y">
                                        {transactions.data.map((row) => (
                                            <tr key={row.id}>
                                                <td className="whitespace-nowrap px-4 py-3 text-xs text-muted-foreground">
                                                    {row.created_at
                                                        ? new Date(
                                                              row.created_at,
                                                          ).toLocaleString('es', {
                                                              dateStyle: 'short',
                                                              timeStyle: 'short',
                                                          })
                                                        : '—'}
                                                </td>
                                                <td className="px-4 py-3">
                                                    <span className="font-medium">
                                                        {typeLabels[row.type]}
                                                    </span>
                                                    {row.type === 'monthly_gain' &&
                                                        row.reference_month && (
                                                            <span className="mt-1 block text-xs text-muted-foreground">
                                                                Mes sistema:{' '}
                                                                <strong className="text-foreground">
                                                                    {row.reference_month}
                                                                </strong>
                                                                {row.investment_month_index !==
                                                                    null &&
                                                                    row.investment_month_index >
                                                                        0 && (
                                                                        <>
                                                                            {' '}
                                                                            · cupo{' '}
                                                                            {
                                                                                row.investment_month_index
                                                                            }
                                                                        </>
                                                                    )}
                                                            </span>
                                                        )}
                                                    {row.type === 'daily_gain' && row.accrual_on && (
                                                        <span className="mt-1 block text-xs text-muted-foreground">
                                                            Día acreditado:{' '}
                                                            <strong className="text-foreground">
                                                                {row.accrual_on}
                                                            </strong>
                                                        </span>
                                                    )}
                                                    {row.type === 'period_accrual' &&
                                                        row.gain_period_start &&
                                                        row.gain_period_end && (
                                                            <span className="mt-1 block text-xs text-muted-foreground">
                                                                Período incluido:{' '}
                                                                <strong className="text-foreground">
                                                                    {row.gain_period_start}
                                                                </strong>{' '}
                                                                →{' '}
                                                                <strong className="text-foreground">
                                                                    {row.gain_period_end}
                                                                </strong>
                                                                {row.accrual_on ? (
                                                                    <>
                                                                        {' '}
                                                                        · cierre registral:{' '}
                                                                        <strong className="text-foreground">
                                                                            {row.accrual_on}
                                                                        </strong>
                                                                    </>
                                                                ) : null}
                                                            </span>
                                                        )}
                                                </td>
                                                <td className="px-4 py-3 font-medium tabular-nums">
                                                    {formatCurrency(Number(row.amount_usd))}
                                                </td>
                                                <td className="px-4 py-3 tabular-nums">
                                                    {formatCurrency(
                                                        Number(row.balance_after_usd),
                                                    )}
                                                </td>
                                                <td className="px-4 py-3 text-xs text-muted-foreground">
                                                    {row.applied_percent !== null ? (
                                                        <span className="tabular-nums">
                                                            {Number(row.applied_percent).toLocaleString(
                                                                'es-US',
                                                                {
                                                                    minimumFractionDigits: 0,
                                                                    maximumFractionDigits: 4,
                                                                },
                                                            )}
                                                            %
                                                        </span>
                                                    ) : (
                                                        '—'
                                                    )}
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                                {transactions.last_page > 1 ? (
                                    <InertiaPaginatorFooter paginator={transactions} />
                                ) : null}
                            </>
                        )}
                    </CardContent>
                </Card>
            </AppPage>
        </>
    );
}

InvestmentTransactions.layout = {
    breadcrumbs: [
        { title: 'Inicio', href: dashboard() },
        { title: 'Mis inversiones', href: '/mis-inversiones' },
        { title: 'Movimientos', href: '#' },
    ],
};
