'use client';

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

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { apiFetch } from '@/lib/api/client';
import { formatCurrency } from '@/lib/utils/currency';

interface Bucket {
  quarterEnd: string;
  endingTenancyCount: number;
  totalAtRisk: number;
  currency: string | null;
}

interface RevenueResponse {
  data: Bucket[];
}

function formatQuarter(iso: string): string {
  const d = new Date(iso);
  const q = Math.floor(d.getMonth() / 3) + 1;
  return `Q${q} ${d.getFullYear()}`;
}

/**
 * Forward-looking projection: sums berth prices for active tenancies
 * whose end-date falls in each quarter through the configured horizon.
 * Highlights renewal-cliff quarters.
 */
export function TenancyRevenueForecastWidget() {
  const { data, isLoading } = useQuery<RevenueResponse>({
    queryKey: ['dashboard', 'tenancy_revenue'],
    queryFn: () => apiFetch<RevenueResponse>('/api/v1/dashboard/tenancy-revenue?horizonQuarters=8'),
    staleTime: 60_000,
  });

  const buckets = data?.data ?? [];
  const maxValue = buckets.reduce((acc, b) => Math.max(acc, b.totalAtRisk), 0);

  return (
    <Card>
      <CardHeader>
        <CardTitle className="text-base">Revenue forecast</CardTitle>
        <CardDescription>
          {buckets.length === 0
            ? 'No fixed-term tenancies expire in the forecast window.'
            : 'Berth value tied to tenancies ending each quarter.'}
        </CardDescription>
      </CardHeader>
      <CardContent>
        {isLoading ? (
          <Skeleton className="h-[200px] w-full" aria-hidden />
        ) : buckets.length === 0 ? (
          <p className="py-8 text-center text-sm text-muted-foreground">
            Nothing expiring in the next 8 quarters.
          </p>
        ) : (
          <ul className="space-y-2">
            {buckets.map((b) => {
              const widthPct = maxValue > 0 ? Math.round((b.totalAtRisk / maxValue) * 100) : 0;
              return (
                <li key={b.quarterEnd} className="space-y-1">
                  <div className="flex items-center justify-between text-xs">
                    <span className="font-medium">{formatQuarter(b.quarterEnd)}</span>
                    <span className="text-muted-foreground">
                      {b.endingTenancyCount} {b.endingTenancyCount === 1 ? 'tenancy' : 'tenancies'}{' '}
                      ·{' '}
                      {b.currency
                        ? formatCurrency(b.totalAtRisk, b.currency, { maxFractionDigits: 0 })
                        : b.totalAtRisk.toLocaleString()}
                    </span>
                  </div>
                  <div className="h-2 overflow-hidden rounded-full bg-muted">
                    <div
                      className="h-full bg-amber-500"
                      style={{ width: `${widthPct}%` }}
                      aria-hidden
                    />
                  </div>
                </li>
              );
            })}
          </ul>
        )}
      </CardContent>
    </Card>
  );
}
