'use client';

import {Card} from '@astryxdesign/core/Card';
import {Grid} from '@astryxdesign/core/Grid';
import {VStack, HStack} from '@astryxdesign/core/Layout';
import {Text} from '@astryxdesign/core/Text';
import {Badge} from '@astryxdesign/core/Badge';
import {Sparkline} from '@/shared/components/charts/Sparkline';
import {ChartCard} from '@/shared/components/charts/ChartCard';
import {StatPair, StatRow} from '@/shared/components/patterns/StatPair';
import {formatCompact, formatInrCompact, formatPct} from '@/shared/utils/format';
import type {StoreComparison as StoreComparisonRow} from '@/features/dashboard/types/dashboard';
import type {Resource} from '@/shared/hooks/useResource';

/**
 * Small multiples, not a five-series chart.
 *
 * This is the palette constraint doing its job: five stores on one axis would
 * need five colours, and the monochrome ramp only separates about three. One
 * card per store is also simply better for the question being asked — "which
 * store is the outlier?" is a comparison of shapes, not of overlapping lines.
 */
export function StoreComparisonPanel({
  resource,
}: {
  resource: Resource<StoreComparisonRow[]>;
}) {
  return (
    <ChartCard
      title="Store comparison"
      subtitle="One card per store — five series on one axis would need five colours"
      resource={resource}
      height={220}
    >
      {(rows) => {
        const best = rows.reduce((a, b) => (b.visitors > a.visitors ? b : a));
        const worst = rows.reduce((a, b) => (b.visitors < a.visitors ? b : a));

        return (
          <Grid columns={{minWidth: 200, repeat: 'fit'}} gap={3}>
            {rows.map((r) => (
              <Card key={r.storeId} variant="muted">
                <VStack gap={2}>
                  <HStack gap={2} vAlign="center" hAlign="between">
                    <Text size="sm" weight="medium">
                      {r.name}
                    </Text>
                    {r.storeId === best.storeId ? (
                      <Badge variant="success" label="Top" />
                    ) : r.storeId === worst.storeId ? (
                      <Badge variant="warning" label="Lowest" />
                    ) : null}
                  </HStack>

                  {/* A visitor count is data, not a section title. */}
                  <Text type="display-3">{formatCompact(r.visitors)}</Text>
                  <Sparkline data={r.trend} dataKey="v" height={34} />

                  <StatRow>
                    <StatPair
                      label="Revenue"
                      value={formatInrCompact(r.revenueInr)}
                    />
                    <StatPair
                      label="Conversion"
                      value={formatPct(r.conversionPct)}
                      align="end"
                    />
                  </StatRow>
                </VStack>
              </Card>
            ))}
          </Grid>
        );
      }}
    </ChartCard>
  );
}
