'use client';

import {
  SegmentedControl,
  SegmentedControlItem,
} from '@astryxdesign/core/SegmentedControl';
import {ChartCard} from '@/components/charts/ChartCard';
import {BarChartView} from '@/components/charts/BarChartView';
import {useResource} from '@/lib/api/useResource';
import {endpoints} from '@/lib/api/client';
import type {Scope} from '@/lib/api/client';
import type {Granularity, PeriodPoint} from '@/lib/api/contracts';
import {formatInrCompact} from '@/lib/format';

/**
 * Weekly / monthly rollup.
 *
 * The granularity is part of the request rather than a client-side regroup:
 * the buckets have to come from the same generator the daily series does, or
 * the weekly totals quietly stop matching the daily chart above them.
 */
export function PerformancePanel({
  scope,
  granularity,
  onGranularityChange,
}: {
  scope: Scope;
  granularity: Granularity;
  onGranularityChange: (g: Granularity) => void;
}) {
  const resource = useResource<PeriodPoint[]>(
    endpoints.dashboardPerformance(scope, granularity),
  );

  return (
    <ChartCard
      title="Performance"
      subtitle={
        granularity === 'weekly'
          ? 'Revenue by ISO week'
          : 'Revenue by calendar month'
      }
      resource={resource}
      actions={
        <SegmentedControl
          value={granularity}
          onChange={(v) => onGranularityChange(v as Granularity)}
          label="Performance granularity"
          size="sm"
        >
          <SegmentedControlItem value="weekly" label="Weekly" />
          <SegmentedControlItem value="monthly" label="Monthly" />
        </SegmentedControl>
      }
    >
      {(rows) => (
        <BarChartView
          data={rows}
          xKey="label"
          yFormat={formatInrCompact}
          series={[{key: 'revenue', label: 'Revenue'}]}
        />
      )}
    </ChartCard>
  );
}
