import { Head, usePage } from '@inertiajs/react';

type Metric = {
    key: string; name: string; unit: string; domain: string;
    value: number | null; freshness: string; explanation: string | null;
};

function format(value: number | null, unit: string): string {
    if (value === null) return '—';
    if (unit === 'currency') return '$' + value.toLocaleString(undefined, { maximumFractionDigits: 0 });
    if (unit === 'percent') return value + '%';
    return value.toLocaleString();
}

const FRESH: Record<string, string> = {
    fresh: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300',
    stale: 'bg-amber-100 text-amber-700 dark:bg-amber-500/15 dark:text-amber-300',
    no_data: 'bg-muted text-muted-foreground',
};

export default function Metrics() {
    const { metrics } = usePage().props as unknown as { metrics: Metric[] };

    return (
        <>
            <Head title="Metrics" />
            <div className="mx-auto w-full max-w-6xl px-6 py-8">
                <header className="mb-8">
                    <h1 className="text-2xl font-semibold tracking-tight text-foreground">Metrics</h1>
                    <p className="mt-1 text-sm text-muted-foreground">
                        Governed metrics — the same definitions your dashboards and AI Analyst use.
                    </p>
                </header>

                {metrics.length === 0 ? (
                    <p className="text-sm text-muted-foreground">No metrics available yet. Connect a data source to populate them.</p>
                ) : (
                    <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                        {metrics.map((m) => (
                            <div key={m.key} className="rounded-xl border border-border bg-card p-5 shadow-sm">
                                <div className="flex items-start justify-between">
                                    <p className="text-sm font-medium text-muted-foreground">{m.name}</p>
                                    <span className={`rounded-full px-2 py-0.5 text-[10px] font-medium ${FRESH[m.freshness] ?? FRESH.no_data}`}>
                                        {m.freshness === 'no_data' ? 'no data' : m.freshness}
                                    </span>
                                </div>
                                <p className="mt-2 text-3xl font-semibold text-foreground">{format(m.value, m.unit)}</p>
                                {m.explanation && <p className="mt-2 text-xs text-muted-foreground">{m.explanation}</p>}
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </>
    );
}
