'use client';

import {Grid} from '@astryxdesign/core/Grid';
import {AsyncBoundary} from '@/components/data/AsyncBoundary';
import {MetricCard} from '@/components/patterns/MetricCard';
import {SkeletonMetricGrid} from '@/components/patterns/LoadingState';
import {ICONS} from '@/lib/icons';
import {useBreakpoint, metricColumns} from '@/lib/breakpoints';
import {useCopilot} from '@/features/copilot/CopilotProvider';
import {formatCompact, formatInrCompact} from '@/lib/format';
import type {Kpi, KpiId} from '@/lib/api/contracts';
import type {Resource} from '@/lib/api/useResource';
import type {IconType} from '@astryxdesign/core/Icon';

const KPI_ICON: Record<KpiId, IconType> = {
  visitors: ICONS.visitors,
  purchases: ICONS.purchases,
  revenue: ICONS.revenue,
  activeRewards: ICONS.activeRewards,
};

/**
 * Four KPIs must lay out 4-up, 2×2, or stacked — never 3+1, which reads as a
 * broken grid. `repeat: 'fit'` cannot express that: at a ~800px workspace it
 * yields exactly three columns whatever minWidth you choose, and the fourth
 * card drops to an orphan row.
 *
 * So the count is computed rather than inferred. The two things that decide
 * the available width are the breakpoint and whether the Copilot panel is
 * taking 320–380px of it, and both are already known here.
 */
export function useMetricColumns(): number {
  const bp = useBreakpoint();
  const {isOpen} = useCopilot();
  // The rule itself lives in lib/breakpoints alongside every other layout
  // threshold, so a breakpoint change is one edit rather than a hunt.
  return metricColumns(bp, isOpen);
}

export function KpiRow({resource}: {resource: Resource<Kpi[]>}) {
  const columns = useMetricColumns();

  return (
    <AsyncBoundary
      resource={resource}
      loading={<SkeletonMetricGrid columns={columns} />}
    >
      {(kpis) => (
        <Grid columns={columns} gap={4}>
          {kpis.map((k) => (
            <MetricCard
              key={k.id}
              label={k.label}
              value={k.value}
              format={k.unit === 'inr' ? formatInrCompact : formatCompact}
              icon={KPI_ICON[k.id]}
              deltaPct={k.deltaPct}
              isRiseGood={k.isRiseGood}
              trend={k.trend}
            />
          ))}
        </Grid>
      )}
    </AsyncBoundary>
  );
}
