/**
 * Margin — the ledger, per block and in total.
 *
 * The table scrolls inside its own pane on narrow screens rather than making
 * the page scroll sideways; a card list would lose the column comparison that
 * is the entire value of this view.
 */
import { useQuery } from '@tanstack/react-query';
import { compactNumber, get, money, moneyExact, percent } from '@/lib/api';
import { Card, CardContent, CardHeader, CardTitle, EmptyState, Skeleton, Stat } from '@/components/ui';

interface MarginReport {
  totals: {
    committedGpuHours: number;
    allocatedGpuHours: number;
    idleGpuHours: number;
    utilisation: number;
    costCents: number;
    revenueCents: number;
    grossMarginCents: number;
    grossMarginPct: number | null;
    marginPerAllocatedGpuHourCents: number | null;
  };
  blocks: {
    commitmentId: string;
    name: string;
    gpuType: string;
    gpuCount: number;
    totalGpuHours: number;
    soldGpuHours: number;
    availableGpuHours: number;
    costPerGpuHourCents: number;
    utilisation: number;
    breakEvenPriceCents: number | null;
  }[];
}

export function Margin() {
  const { data, isLoading } = useQuery({
    queryKey: ['margin'],
    queryFn: () => get<MarginReport>('/api/capacity/margin'),
  });

  if (isLoading) return <Skeleton className="h-96" />;
  if (!data || data.blocks.length === 0) {
    return (
      <EmptyState
        title="No capacity to report on"
        description="Margin is computed from capacity commitments and the allocations against them."
      />
    );
  }

  const t = data.totals;

  return (
    <div className="space-y-6">
      <header>
        <h1 className="text-xl font-semibold tracking-tight sm:text-2xl">Margin</h1>
        <p className="mt-1 max-w-2xl text-sm text-muted">
          Revenue from what we sold, against the full cost of what we bought.
        </p>
      </header>

      <section className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <Stat label="Revenue" value={money(t.revenueCents)} />
        <Stat label="Cost" value={money(t.costCents)} hint="Full commitment" />
        <Stat
          label="Gross margin"
          value={money(t.grossMarginCents)}
          hint={percent(t.grossMarginPct, 1)}
          tone={t.grossMarginCents >= 0 ? 'positive' : 'danger'}
        />
        <Stat
          label="Per sold GPU-hour"
          value={moneyExact(t.marginPerAllocatedGpuHourCents)}
          hint={`${percent(t.utilisation, 1)} utilised`}
        />
      </section>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">By commitment</CardTitle>
        </CardHeader>
        <CardContent className="px-0 sm:px-0">
          <div className="scroll-x">
            <table className="w-full min-w-[720px] text-sm">
              <thead>
                <tr className="border-b border-border text-left text-xs uppercase tracking-wide text-muted">
                  <th className="px-4 pb-2 font-medium sm:px-5">Commitment</th>
                  <th className="px-4 pb-2 text-right font-medium">Sold</th>
                  <th className="px-4 pb-2 text-right font-medium">Free</th>
                  <th className="px-4 pb-2 text-right font-medium">Utilisation</th>
                  <th className="px-4 pb-2 text-right font-medium">Cost/hr</th>
                  <th className="px-4 pb-2 text-right font-medium sm:px-5">Break even</th>
                </tr>
              </thead>
              <tbody>
                {data.blocks.map((block) => (
                  <tr key={block.commitmentId} className="border-b border-border/60 last:border-0">
                    <td className="px-4 py-3 sm:px-5">
                      <div className="font-medium">{block.name}</div>
                      <div className="text-xs text-muted">
                        {block.gpuCount}× {block.gpuType}
                      </div>
                    </td>
                    <td className="nums px-4 py-3 text-right">
                      {compactNumber(block.soldGpuHours)}
                    </td>
                    <td className="nums px-4 py-3 text-right">
                      {compactNumber(block.availableGpuHours)}
                    </td>
                    <td
                      className={[
                        'nums px-4 py-3 text-right font-medium',
                        block.utilisation < 0.5 ? 'text-warning' : '',
                      ].join(' ')}
                    >
                      {percent(block.utilisation)}
                    </td>
                    <td className="nums px-4 py-3 text-right">
                      {moneyExact(block.costPerGpuHourCents)}
                    </td>
                    <td className="nums px-4 py-3 text-right sm:px-5">
                      {block.breakEvenPriceCents == null
                        ? '—'
                        : moneyExact(block.breakEvenPriceCents)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
