import { Head, router } from '@inertiajs/react';
import { Activity, CircleAlert, Coins, Database, Hash } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import type { FormEvent } from 'react';
import { Bar, BarChart, CartesianGrid, Tooltip, XAxis, YAxis } from 'recharts';
import Heading from '@/components/heading';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { ChartContainer, ChartTooltipContent } from '@/components/ui/chart';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { index as aiUsage } from '@/routes/admin/ai-usage';

type UsageLog = {
    id: number;
    request_type: string;
    agent: string;
    provider: string | null;
    model: string | null;
    prompt: string;
    prompt_tokens: number | null;
    completion_tokens: number | null;
    total_tokens: number | null;
    cost: string | null;
    currency: string | null;
    status: string;
    error: string | null;
    created_at: string;
    user?: { name: string } | null;
    company?: { name: string } | null;
};

type Props = {
    filters: { from: string; to: string; request_type: string };
    summary: {
        requests: number;
        completed: number;
        failed: number;
        tokens: number;
        cost: string;
    };
    daily: Array<{ date: string; requests: number; cost: number }>;
    providers: Array<{ provider: string; requests: number; cost: number }>;
    logs: {
        data: UsageLog[];
        links: Array<{ url: string | null; label: string; active: boolean }>;
    };
};

const chartConfig = {
    requests: { label: 'Requests', color: 'var(--chart-1)' },
    cost: { label: 'Cost', color: 'var(--chart-2)' },
};

const summaryCards: Array<{ label: string; icon: LucideIcon }> = [
    { label: 'Requests', icon: Hash },
    { label: 'Completed', icon: Activity },
    { label: 'Failed', icon: CircleAlert },
    { label: 'Tokens', icon: Database },
    { label: 'Estimated cost', icon: Coins },
];

function formatCost(value: number | string | null, currency = 'USD'): string {
    if (value === null) {
        return '—';
    }

    return new Intl.NumberFormat(undefined, {
        style: 'currency',
        currency,
        maximumFractionDigits: 6,
    }).format(Number(value));
}

function requestLabel(value: string): string {
    return value === 'growth_iq_chat'
        ? 'Growth IQ chat'
        : 'Growth Score advisor';
}

export default function AiUsagePage({
    filters,
    summary,
    daily,
    providers,
    logs,
}: Props) {
    function applyFilters(event: FormEvent<HTMLFormElement>) {
        event.preventDefault();
        const formData = new FormData(event.currentTarget);

        router.get(
            aiUsage(),
            {
                from: formData.get('from') || undefined,
                to: formData.get('to') || undefined,
                request_type: formData.get('request_type') || undefined,
            },
            { preserveState: true, replace: true },
        );
    }

    return (
        <>
            <Head title="AI Usage" />
            <div className="space-y-6">
                <Heading
                    variant="small"
                    title="AI Usage"
                    description="Monitor Growth IQ requests, token consumption, and estimated provider costs."
                />

                <Card>
                    <CardContent className="pt-6">
                        <form
                            onSubmit={applyFilters}
                            className="grid gap-4 md:grid-cols-[1fr_1fr_1fr_auto]"
                        >
                            <div className="grid gap-2">
                                <Label htmlFor="from">From</Label>
                                <Input
                                    id="from"
                                    name="from"
                                    type="date"
                                    defaultValue={filters.from}
                                />
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="to">To</Label>
                                <Input
                                    id="to"
                                    name="to"
                                    type="date"
                                    defaultValue={filters.to}
                                />
                            </div>
                            <div className="grid gap-2">
                                <Label htmlFor="request_type">
                                    Request type
                                </Label>
                                <select
                                    id="request_type"
                                    name="request_type"
                                    defaultValue={filters.request_type}
                                    className="h-9 rounded-md border border-input bg-background px-3 text-sm"
                                >
                                    <option value="">All requests</option>
                                    <option value="growth_iq_chat">
                                        Growth IQ chat
                                    </option>
                                    <option value="growth_score_advisor">
                                        Growth Score advisor
                                    </option>
                                </select>
                            </div>
                            <Button type="submit" className="self-end">
                                Apply filters
                            </Button>
                        </form>
                    </CardContent>
                </Card>

                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-5">
                    {summaryCards.map(({ label, icon: Icon }, index) => {
                        const values = [
                            summary.requests,
                            summary.completed,
                            summary.failed,
                            summary.tokens.toLocaleString(),
                            formatCost(summary.cost),
                        ];

                        return (
                            <Card key={label}>
                                <CardContent className="flex items-center justify-between gap-3 pt-6">
                                    <div>
                                        <p className="text-sm text-muted-foreground">
                                            {label}
                                        </p>
                                        <p className="mt-1 text-2xl font-semibold">
                                            {values[index]}
                                        </p>
                                    </div>
                                    <Icon className="size-5 text-muted-foreground" />
                                </CardContent>
                            </Card>
                        );
                    })}
                </div>

                <div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
                    <Card>
                        <CardHeader>
                            <CardTitle>Usage over time</CardTitle>
                        </CardHeader>
                        <CardContent>
                            {daily.length === 0 ? (
                                <div className="flex h-64 items-center justify-center text-sm text-muted-foreground">
                                    No usage recorded for this period.
                                </div>
                            ) : (
                                <ChartContainer
                                    config={chartConfig}
                                    className="aspect-auto h-64 w-full"
                                >
                                    <BarChart
                                        data={daily}
                                        margin={{ left: 8, right: 8 }}
                                    >
                                        <CartesianGrid vertical={false} />
                                        <XAxis
                                            dataKey="date"
                                            tickLine={false}
                                            axisLine={false}
                                        />
                                        <YAxis
                                            allowDecimals={false}
                                            tickLine={false}
                                            axisLine={false}
                                        />
                                        <Tooltip
                                            content={
                                                <ChartTooltipContent
                                                    valueFormatter={(value) =>
                                                        Number(
                                                            value,
                                                        ).toLocaleString()
                                                    }
                                                />
                                            }
                                        />
                                        <Bar
                                            dataKey="requests"
                                            fill="var(--color-requests)"
                                            radius={[4, 4, 0, 0]}
                                        />
                                    </BarChart>
                                </ChartContainer>
                            )}
                        </CardContent>
                    </Card>
                    <Card>
                        <CardHeader>
                            <CardTitle>Provider breakdown</CardTitle>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            {providers.length === 0 ? (
                                <p className="text-sm text-muted-foreground">
                                    No provider usage recorded.
                                </p>
                            ) : (
                                providers.map((provider) => (
                                    <div
                                        key={provider.provider}
                                        className="flex items-center justify-between gap-4"
                                    >
                                        <div>
                                            <p className="font-medium capitalize">
                                                {provider.provider}
                                            </p>
                                            <p className="text-xs text-muted-foreground">
                                                {provider.requests} requests
                                            </p>
                                        </div>
                                        <span className="font-mono text-sm">
                                            {formatCost(provider.cost)}
                                        </span>
                                    </div>
                                ))
                            )}
                        </CardContent>
                    </Card>
                </div>

                <Card>
                    <CardHeader>
                        <CardTitle>Request logs</CardTitle>
                    </CardHeader>
                    <CardContent>
                        <div className="overflow-x-auto">
                            <table className="w-full text-left text-sm">
                                <thead className="border-b text-xs tracking-wide text-muted-foreground uppercase">
                                    <tr>
                                        <th className="px-3 py-3">Request</th>
                                        <th className="px-3 py-3">
                                            Company / user
                                        </th>
                                        <th className="px-3 py-3">Model</th>
                                        <th className="px-3 py-3">Tokens</th>
                                        <th className="px-3 py-3">Cost</th>
                                        <th className="px-3 py-3">Status</th>
                                        <th className="px-3 py-3">Created</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y">
                                    {logs.data.map((log) => (
                                        <tr key={log.id} className="align-top">
                                            <td className="max-w-xs px-3 py-3">
                                                <p className="font-medium">
                                                    {requestLabel(
                                                        log.request_type,
                                                    )}
                                                </p>
                                                <p
                                                    className="mt-1 truncate text-muted-foreground"
                                                    title={log.prompt}
                                                >
                                                    {log.prompt}
                                                </p>
                                            </td>
                                            <td className="px-3 py-3">
                                                <p>
                                                    {log.company?.name ?? '—'}
                                                </p>
                                                <p className="text-xs text-muted-foreground">
                                                    {log.user?.name ?? 'System'}
                                                </p>
                                            </td>
                                            <td className="px-3 py-3">
                                                <p>
                                                    {log.provider ?? 'Unknown'}
                                                </p>
                                                <p className="text-xs text-muted-foreground">
                                                    {log.model ?? '—'}
                                                </p>
                                            </td>
                                            <td className="px-3 py-3 font-mono">
                                                {(
                                                    log.total_tokens ?? 0
                                                ).toLocaleString()}
                                            </td>
                                            <td className="px-3 py-3 font-mono">
                                                {formatCost(
                                                    log.cost,
                                                    log.currency ?? 'USD',
                                                )}
                                            </td>
                                            <td className="px-3 py-3">
                                                <Badge
                                                    variant={
                                                        log.status ===
                                                        'completed'
                                                            ? 'secondary'
                                                            : 'destructive'
                                                    }
                                                >
                                                    {log.status}
                                                </Badge>
                                            </td>
                                            <td className="px-3 py-3 text-xs whitespace-nowrap">
                                                {new Date(
                                                    log.created_at,
                                                ).toLocaleString()}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                        {logs.data.length === 0 && (
                            <p className="py-8 text-center text-sm text-muted-foreground">
                                No request logs found.
                            </p>
                        )}
                        {logs.links.length > 3 && (
                            <nav
                                className="mt-4 flex flex-wrap gap-2"
                                aria-label="Pagination"
                            >
                                {logs.links.map((link) => (
                                    <Button
                                        key={link.label}
                                        variant={
                                            link.active ? 'default' : 'outline'
                                        }
                                        size="sm"
                                        disabled={!link.url}
                                        asChild={Boolean(link.url)}
                                    >
                                        {link.url ? (
                                            <a href={link.url}>
                                                {link.label.replace(
                                                    /&laquo;|&raquo;/g,
                                                    '',
                                                )}
                                            </a>
                                        ) : (
                                            <span>
                                                {link.label.replace(
                                                    /&laquo;|&raquo;/g,
                                                    '',
                                                )}
                                            </span>
                                        )}
                                    </Button>
                                ))}
                            </nav>
                        )}
                    </CardContent>
                </Card>
            </div>
        </>
    );
}

AiUsagePage.layout = {
    breadcrumbs: [{ title: 'AI Usage', href: aiUsage() }],
};
