import { Head } from '@inertiajs/react';
import { Copy, LinkIcon, UsersRound } from 'lucide-react';
import { useState } from 'react';
import {
    AppPage,
    AppPageHeader,
    AppPageTitleBlock,
    appCardAccentClass,
} 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 { Input } from '@/components/ui/input';
import { dashboard } from '@/routes';

type ReferralSummary = {
    code: string;
    link: string;
    direct_count: number;
    indirect_count: number;
    total_earnings_usd: string;
    direct_earnings_usd: string;
    indirect_earnings_usd: string;
};

type ReferralRow = {
    id: number;
    name: string;
    email: string;
    via: string | null;
    created_at: string | null;
    earnings_usd: string;
    earnings_count: number;
};

type EarningRow = {
    id: number;
    level: number;
    amount_usd: string;
    base_percent: string | null;
    source_investor: string;
    source_investor_email: string | null;
    source_investment_txid: string;
    created_at: string | null;
};

type PropsDisabled = {
    referral_program_enabled: false;
};

type PropsEnabled = {
    referral_program_enabled: true;
    referral: ReferralSummary;
    direct_referrals: ReferralRow[];
    indirect_referrals: ReferralRow[];
    earnings: EarningRow[];
};

type Props = PropsDisabled | PropsEnabled;

function formatDate(value: string | null): string {
    if (!value) return '—';

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

function ReferralTable({ rows, indirect = false }: { rows: ReferralRow[]; indirect?: boolean }) {
    if (rows.length === 0) {
        return (
            <p className="rounded-xl border border-dashed p-6 text-center text-muted-foreground text-sm">
                Aún no hay referidos en esta categoría.
            </p>
        );
    }

    return (
        <div className="overflow-x-auto rounded-xl border border-border">
            <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">Usuario</th>
                        {indirect ? <th className="px-4 py-3 font-medium">Vía referido</th> : null}
                        <th className="px-4 py-3 font-medium">Alta</th>
                        <th className="px-4 py-3 font-medium tabular-nums">Comisiones</th>
                        <th className="px-4 py-3 font-medium tabular-nums">Ganancia</th>
                    </tr>
                </thead>
                <tbody className="divide-y divide-border">
                    {rows.map((row) => (
                        <tr key={row.id}>
                            <td className="px-4 py-3">
                                <div className="font-medium">{row.name || '—'}</div>
                                <div className="text-muted-foreground text-xs">{row.email}</div>
                            </td>
                            {indirect ? <td className="px-4 py-3 text-muted-foreground">{row.via}</td> : null}
                            <td className="px-4 py-3 text-muted-foreground">{formatDate(row.created_at)}</td>
                            <td className="px-4 py-3 tabular-nums">{row.earnings_count}</td>
                            <td className="px-4 py-3 font-semibold tabular-nums">{row.earnings_usd} US$</td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
}

export default function ReferralsIndex(props: Props) {
    const [copied, setCopied] = useState(false);

    if (!props.referral_program_enabled) {
        return (
            <>
                <Head title="Referidos" />

                <AppPage>
                    <AppPageHeader className="items-start sm:items-start">
                        <div className="flex w-full items-start gap-3">
                            <div className="flex size-10 shrink-0 items-center justify-center rounded-xl border border-border bg-muted/60">
                                <UsersRound aria-hidden className="size-5 text-primary" />
                            </div>
                            <AppPageTitleBlock
                                title="Referidos"
                                description="El programa de referidos no está habilitado en tu cuenta. Un administrador puede activarlo al editar tu perfil en el panel de administración."
                                descriptionClassName="text-sm"
                            />
                        </div>
                    </AppPageHeader>

                    <Card>
                        <CardHeader>
                            <CardTitle className="text-base">Acceso restringido</CardTitle>
                            <CardDescription>
                                Cuando recibas el alta, podrás compartir tu enlace y ver comisiones generadas por la
                                red.
                            </CardDescription>
                        </CardHeader>
                    </Card>
                </AppPage>
            </>
        );
    }

    const { referral, direct_referrals, indirect_referrals, earnings } = props;

    function copyLink() {
        void navigator.clipboard.writeText(referral.link);
        setCopied(true);
        window.setTimeout(() => setCopied(false), 1800);
    }

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

            <AppPage>
                <AppPageHeader className="items-start sm:items-start">
                    <div className="flex w-full items-start gap-3">
                        <div className="flex size-10 shrink-0 items-center justify-center rounded-xl border border-border bg-muted/60">
                            <UsersRound aria-hidden className="size-5 text-primary" />
                        </div>
                        <AppPageTitleBlock
                            title="Referidos"
                            description="Comparte tu enlace. Recibes comisiones sobre las ganancias acreditadas a inversiones confirmadas de tu red (acreditación diaria o por período mensual, según configura la plataforma). Los porcentajes vigentes aparecen en la política comercial / administración."
                            descriptionClassName="text-sm"
                        />
                    </div>
                </AppPageHeader>

                <Card className={appCardAccentClass}>
                    <CardHeader>
                        <CardTitle className="flex items-center gap-2 text-base">
                            <LinkIcon className="size-4" />
                            Tu enlace de referido
                        </CardTitle>
                        <CardDescription>
                            También puedes compartir solo el código: <strong>{referral.code}</strong>.
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-3">
                        <div className="flex rounded-md border bg-background">
                            <Input className="border-0 font-mono text-xs shadow-none" readOnly value={referral.link} />
                            <Button type="button" variant="ghost" onClick={copyLink}>
                                <Copy className="size-4" />
                                <span className="sr-only">Copiar enlace</span>
                            </Button>
                        </div>
                        {copied ? <p className="text-primary text-xs">Enlace copiado.</p> : null}
                    </CardContent>
                </Card>

                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    <Card>
                        <CardContent className="p-4">
                            <p className="text-muted-foreground text-sm">Directos</p>
                            <p className="mt-1 text-2xl font-semibold tabular-nums">{referral.direct_count}</p>
                        </CardContent>
                    </Card>
                    <Card>
                        <CardContent className="p-4">
                            <p className="text-muted-foreground text-sm">Indirectos</p>
                            <p className="mt-1 text-2xl font-semibold tabular-nums">{referral.indirect_count}</p>
                        </CardContent>
                    </Card>
                    <Card>
                        <CardContent className="p-4">
                            <p className="text-muted-foreground text-sm">Ganancia directa</p>
                            <p className="mt-1 text-2xl font-semibold tabular-nums">{referral.direct_earnings_usd} US$</p>
                        </CardContent>
                    </Card>
                    <Card>
                        <CardContent className="p-4">
                            <p className="text-muted-foreground text-sm">Ganancia indirecta</p>
                            <p className="mt-1 text-2xl font-semibold tabular-nums">{referral.indirect_earnings_usd} US$</p>
                        </CardContent>
                    </Card>
                </div>

                <Card>
                    <CardHeader>
                        <CardTitle>Referidos directos</CardTitle>
                        <CardDescription>Usuarios registrados con tu código o enlace.</CardDescription>
                    </CardHeader>
                    <CardContent>
                        <ReferralTable rows={direct_referrals} />
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader>
                        <CardTitle>Referidos indirectos</CardTitle>
                        <CardDescription>Usuarios referidos por tus referidos directos.</CardDescription>
                    </CardHeader>
                    <CardContent>
                        <ReferralTable rows={indirect_referrals} indirect />
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader>
                        <CardTitle>Últimas comisiones acreditadas</CardTitle>
                        <CardDescription>
                            Se generan cuando la plataforma acredita una ganancia a una inversión activa referida (
                            día a día o en el cierre mensual, según el modo vigente).
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-3">
                        {earnings.length === 0 ? (
                            <p className="rounded-xl border border-dashed p-6 text-center text-muted-foreground text-sm">
                                Todavía no hay comisiones acreditadas.
                            </p>
                        ) : (
                            <div className="overflow-x-auto rounded-xl border border-border">
                                <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-3 font-medium">Nivel</th>
                                            <th className="px-4 py-3 font-medium">Origen</th>
                                            <th className="px-4 py-3 font-medium">Inversión</th>
                                            <th className="px-4 py-3 font-medium tabular-nums">%</th>
                                            <th className="px-4 py-3 font-medium tabular-nums">Monto</th>
                                            <th className="px-4 py-3 font-medium">Fecha</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-border">
                                        {earnings.map((earning) => (
                                            <tr key={earning.id}>
                                                <td className="px-4 py-3">
                                                    <Badge variant="secondary">
                                                        {earning.level === 1 ? 'Directo' : 'Indirecto'}
                                                    </Badge>
                                                </td>
                                                <td className="px-4 py-3">
                                                    <div>{earning.source_investor}</div>
                                                    <div className="text-muted-foreground text-xs">
                                                        {earning.source_investor_email}
                                                    </div>
                                                </td>
                                                <td className="px-4 py-3 font-mono text-xs">
                                                    {earning.source_investment_txid}
                                                </td>
                                                <td className="px-4 py-3 tabular-nums">{earning.base_percent ?? '—'}</td>
                                                <td className="px-4 py-3 font-semibold tabular-nums">{earning.amount_usd} US$</td>
                                                <td className="px-4 py-3 text-muted-foreground">{formatDate(earning.created_at)}</td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        )}
                    </CardContent>
                </Card>
            </AppPage>
        </>
    );
}

ReferralsIndex.layout = {
    breadcrumbs: [
        { title: 'Inicio', href: dashboard() },
        { title: 'Referidos', href: '/referidos' },
    ],
};
