import { Head, usePage } from '@inertiajs/react';
import { ChartWidget } from '@/components/widgets/ChartWidget';
import { TrendWidget } from '@/components/widgets/TrendWidget';

type Widget = {
    id?: string; type: string; title?: string; metric?: string;
    data?: { value: number | null; unit: string; period?: { start: string; end: string }; change_percent?: number | null };
};

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

export default function DashboardShow() {
    const { dashboard, widgets } = usePage().props as unknown as {
        dashboard: { name: string }; widgets: Widget[];
    };

    return (
        <>
            <Head title={dashboard.name} />
            <div className="mx-auto w-full max-w-6xl px-6 py-8">
                <h1 className="mb-6 text-2xl font-semibold tracking-tight text-foreground">{dashboard.name}</h1>
                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                    {widgets.map((w, i) => {
                        if (['line', 'bar', 'area'].includes(w.type) && w.metric) {
                            return <ChartWidget key={i} metric={w.metric} title={w.title ?? w.metric} type={w.type as 'line' | 'bar' | 'area'} />;
                        }
                        if (w.type === 'trend' && w.metric) {
                            return <TrendWidget key={i} title={w.title ?? w.metric} value={w.data?.value ?? null} unit={w.data?.unit} changePercent={w.data?.change_percent} />;
                        }
                        // default KPI
                        return (
                            <div key={i} className="rounded-xl border border-border bg-card p-5 shadow-sm">
                                <p className="text-sm font-medium text-muted-foreground">{w.title ?? w.metric}</p>
                                <p className="mt-2 text-3xl font-semibold text-foreground">{fmt(w.data?.value, w.data?.unit ?? 'number')}</p>
                                {w.data?.period && <p className="mt-2 text-xs text-muted-foreground">{w.data.period.start} → {w.data.period.end}</p>}
                            </div>
                        );
                    })}
                </div>
            </div>
        </>
    );
}
