'use client';

import {Grid} from '@astryxdesign/core/Grid';
import {MetricCard} from '@/shared/components/patterns/MetricCard';
import {ICONS} from '@/shared/utils/icons';
import {formatCount, formatInrCompact, formatPct} from '@/shared/utils/format';
import {useWorkspace} from '@/shared/providers/WorkspaceProvider';
import {getCommerceKpis} from '../services/commerceService';

export function CommerceKpiRow() {
  const {storeId, range} = useWorkspace();
  const kpis = getCommerceKpis(storeId, range);

  const kpiList = [
    {
      label: 'Total Revenue',
      value: kpis.revenue.rawValue,
      format: formatInrCompact,
      icon: ICONS.revenue,
      deltaPct: 14.2,
    },
    {
      label: 'Total Orders',
      value: kpis.orders.rawValue,
      format: formatCount,
      icon: ICONS.purchases,
      deltaPct: 8.5,
    },
    {
      label: 'Avg Order Value',
      value: kpis.aov.rawValue,
      format: formatInrCompact,
      icon: ICONS.purchases,
      deltaPct: 5.1,
    },
    {
      label: 'Net Sales',
      value: kpis.netSales.rawValue,
      format: formatInrCompact,
      icon: ICONS.revenue,
      deltaPct: 13.9,
    },
    {
      label: 'Refunds',
      value: kpis.refunds.rawValue,
      format: formatInrCompact,
      icon: ICONS.alert,
      deltaPct: -2.4,
      isRiseGood: false,
    },
    {
      label: 'Conversion',
      value: kpis.conversion.rawValue,
      format: (v: number) => formatPct(v, 1),
      icon: ICONS.conversion,
      deltaPct: 1.4,
    },
  ];

  return (
    <Grid columns={{minWidth: 220, max: 6, repeat: 'fit'}} gap={4}>
      {kpiList.map((kpi) => (
        <MetricCard
          key={kpi.label}
          label={kpi.label}
          value={kpi.value}
          format={kpi.format}
          icon={kpi.icon}
          deltaPct={kpi.deltaPct}
          isRiseGood={kpi.isRiseGood}
        />
      ))}
    </Grid>
  );
}
