'use client';

import {
  SegmentedControl,
  SegmentedControlItem,
} from '@astryxdesign/core/SegmentedControl';
import {ChartCard} from '@/shared/components/charts/ChartCard';
import {BarChartView} from '@/shared/components/charts/BarChartView';
import {useDashboardPerformance} from '@/features/dashboard/hooks/useDashboard';
import type {Granularity} from '@/features/dashboard/types/dashboard';
import {formatInrCompact} from '@/shared/utils/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({
  granularity,
  onGranularityChange,
}: {
  granularity: Granularity;
  onGranularityChange: (g: Granularity) => void;
}) {
  // Scope comes from the workspace via the hook rather than from a prop: the
  // panel is always showing the same store and period as the page around it,
  // and threading that through as an argument only created a way for them to
  // disagree.
  const resource = useDashboardPerformance(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>
  );
}
