'use client';

import { useQuery } from '@tanstack/react-query';

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

interface StageBreakdownRow {
  stage: string;
  count: number;
  weightedValue: number;
}

interface ForecastData {
  totalWeightedValue: number;
  stageBreakdown: StageBreakdownRow[];
  weightsSource: 'db' | 'default';
}

const formatUsd = (value: number) => formatCurrency(value, 'USD', { maxFractionDigits: 0 });

function RevenueForecastInner() {
  const { data, isLoading } = useQuery<ForecastData>({
    queryKey: ['dashboard', 'forecast'],
    queryFn: () => apiFetch<ForecastData>('/api/v1/dashboard/forecast'),
    staleTime: 60_000,
    retry: 2,
  });

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

  const activeStages = (data?.stageBreakdown ?? []).filter((s) => s.count > 0);

  return (
    <Card className="h-full">
      <CardHeader className="flex flex-row items-start justify-between gap-2">
        <CardTitle className="text-base">Revenue Forecast</CardTitle>
        {data?.weightsSource === 'default' && (
          <Badge variant="secondary" className="shrink-0 text-xs">
            Using default weights
          </Badge>
        )}
      </CardHeader>
      <CardContent className="space-y-4">
        <div>
          <p className="text-xs text-muted-foreground">Weighted Pipeline Value</p>
          <p className="text-2xl font-bold">{formatUsd(data?.totalWeightedValue ?? 0)}</p>
        </div>

        {activeStages.length > 0 && (
          <div className="space-y-2">
            {activeStages.map((s) => (
              <div key={s.stage} className="flex items-center justify-between text-sm">
                <span className="text-muted-foreground">
                  {stageLabel(s.stage)}
                  <span className="ml-1 text-xs">({s.count})</span>
                </span>
                <span className="font-medium tabular-nums">{formatUsd(s.weightedValue)}</span>
              </div>
            ))}
          </div>
        )}

        {activeStages.length === 0 && (
          <p className="text-sm text-muted-foreground">No active interests with linked berths.</p>
        )}
      </CardContent>
    </Card>
  );
}

export function RevenueForecast() {
  return (
    <WidgetErrorBoundary>
      <RevenueForecastInner />
    </WidgetErrorBoundary>
  );
}
