'use client';

import { useQuery } from '@tanstack/react-query';
import { DollarSign, LayoutGrid, TrendingUp, Users } from 'lucide-react';

import { apiFetch } from '@/lib/api/client';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { CardSkeleton } from '@/components/shared/loading-skeleton';
import { WidgetErrorBoundary } from './widget-error-boundary';

interface KpiData {
  totalClients: number;
  activeInterests: number;
  pipelineValueUsd: number;
  occupancyRate: number;
}

function formatCurrency(value: number): string {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    maximumFractionDigits: 0,
  }).format(value);
}

function formatPercent(value: number): string {
  return `${value.toFixed(1)}%`;
}

export function KpiCards() {
  const { data, isLoading, isError } = useQuery<KpiData>({
    queryKey: ['dashboard', 'kpis'],
    queryFn: () => apiFetch<KpiData>('/api/v1/dashboard/kpis'),
    staleTime: 60_000,
    retry: 2,
  });

  if (isLoading) {
    return (
      <>
        <CardSkeleton />
        <CardSkeleton />
        <CardSkeleton />
        <CardSkeleton />
      </>
    );
  }

  const kpis = [
    {
      label: 'Total Clients',
      value: isError ? '—' : String(data?.totalClients ?? 0),
      icon: Users,
    },
    {
      label: 'Active Interests',
      value: isError ? '—' : String(data?.activeInterests ?? 0),
      icon: TrendingUp,
    },
    {
      label: 'Pipeline Value',
      value: isError ? '—' : formatCurrency(data?.pipelineValueUsd ?? 0),
      icon: DollarSign,
    },
    {
      label: 'Occupancy Rate',
      value: isError ? '—' : formatPercent(data?.occupancyRate ?? 0),
      icon: LayoutGrid,
    },
  ];

  return (
    <>
      {kpis.map(({ label, value, icon: Icon }) => (
        <Card key={label}>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">
              {label}
            </CardTitle>
            <Icon className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{value}</div>
            <div className="mt-1 h-1 w-8 rounded-full bg-muted" />
          </CardContent>
        </Card>
      ))}
    </>
  );
}

export function KpiCardsWithBoundary() {
  return (
    <WidgetErrorBoundary>
      <KpiCards />
    </WidgetErrorBoundary>
  );
}
