'use client';

import { useCallback, useEffect, useState } from 'react';
import dynamic from 'next/dynamic';
import { PageHeader, LoadingSpinner } from '@bytelyst/dashboard-components';
import { KpiCard } from '@bytelyst/data-viz';
import { Reveal, NumberFlow } from '@bytelyst/motion';
import { Button, Skeleton, toast } from '@/components/ui/Primitives';
import { useAuth } from '@/lib/auth-context';
import { useProduct } from '@/lib/product-context';
import { getStats, type TrackerStats } from '@/lib/tracker-client';
import { overviewKpis } from '@/lib/overview-charts';

// Heavy SVG chart surface — kept out of the initial route bundle (UX-4 / CC.7).
const OverviewCharts = dynamic(() => import('@/components/overview-charts'), {
  ssr: false,
  loading: () => <Skeleton className="h-64 w-full" />,
});

export default function DashboardOverview() {
  const { token } = useAuth();
  const { productId } = useProduct();
  const [stats, setStats] = useState<TrackerStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadStats = useCallback(async () => {
    if (!token) return;
    setLoading(true);
    setError(null);
    try {
      const data = await getStats();
      setStats(data);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Unknown error';
      setStats(null);
      setError(message);
      toast({ type: 'error', title: 'Failed to load stats', description: message });
    } finally {
      setLoading(false);
    }
  }, [token]);

  useEffect(() => {
    void loadStats();
  }, [loadStats, productId]);

  const kpis = stats ? overviewKpis(stats) : null;

  return (
    <div className="space-y-6">
      <PageHeader title="Dashboard" />
      <p className="-mt-4 text-sm text-muted-foreground">Overview of all tracked items</p>

      {error ? (
        <div className="rounded-2xl border border-destructive/30 bg-card p-6 shadow-sm">
          <h2 className="text-lg font-semibold text-foreground">Could not load dashboard</h2>
          <p className="mt-2 text-sm text-muted-foreground">
            {error}. Check platform-service health or retry the request.
          </p>
          <Button className="mt-4" onClick={() => void loadStats()}>
            Retry
          </Button>
        </div>
      ) : stats && kpis ? (
        <div className="space-y-4">
          {/* KPI row */}
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            {[
              { label: `Total · ${stats.productId}`, value: kpis.total },
              { label: 'Open', value: kpis.open },
              { label: 'In Progress', value: kpis.inProgress },
              { label: 'Done', value: kpis.done },
            ].map((k, i) => (
              <Reveal key={k.label} delay={i * 60}>
                <KpiCard label={k.label} value={<NumberFlow value={k.value} />} />
              </Reveal>
            ))}
          </div>

          {/* Charts */}
          <Reveal delay={120}>
            <OverviewCharts stats={stats} />
          </Reveal>
        </div>
      ) : loading ? (
        <div className="flex justify-center py-10">
          <LoadingSpinner />
        </div>
      ) : null}
    </div>
  );
}
