import { Group, Paper, Text } from "@mantine/core";

import {
  OverviewKpiCard,
  type KpiGraphVariant,
  type OverviewKpiItem,
} from "./OverviewKpiCard";

/** Rotate mini-graph types per card so each strip reads as a lively mix. */
const VARIANT_CYCLE: KpiGraphVariant[] = ["area", "line", "ring"];

/** Cohesive accent rotation — gold-forward with an orange and neutral break. */
const ACCENT_CYCLE: NonNullable<OverviewKpiItem["accent"]>[] = [
  "gold",
  "orange",
  "default",
];

interface OverviewKpiStripProps {
  title?: string;
  items: OverviewKpiItem[];
}

/** Parse a numeric magnitude out of a KPI value (handles formatted currency strings). */
function toNumber(value: number | string): number {
  if (typeof value === "number") return value;
  const parsed = Number(String(value).replace(/[^0-9.-]/g, ""));
  return Number.isFinite(parsed) ? parsed : 0;
}

export function OverviewKpiStrip({ title, items }: OverviewKpiStripProps) {
  const max = Math.max(...items.map((item) => toNumber(item.value)), 0);

  return (
    <Paper
      p="lg"
      radius="lg"
      withBorder
      style={{
        background: "#ffffff",
        border: "1px solid var(--mantine-color-gray-2)",
      }}
    >
      {title && (
        <Text size="sm" fw={600} mb="md" c="dimmed">
          {title}
        </Text>
      )}
      <Group gap="md" align="stretch" wrap="wrap">
        {items.map((item, index) => (
          <OverviewKpiCard
            key={item.label}
            item={{
              ...item,
              accent: ACCENT_CYCLE[index % ACCENT_CYCLE.length],
              variant: item.variant ?? VARIANT_CYCLE[index % VARIANT_CYCLE.length],
              progress:
                item.progress ?? (max > 0 ? toNumber(item.value) / max : 0),
            }}
          />
        ))}
      </Group>
    </Paper>
  );
}
