import { Box, Group, Text } from "@mantine/core";
import type { LucideIcon } from "lucide-react";
import { memo } from "react";
import { cv } from "../constants";

/** Accent families map a KPI to a soft tile + strong ink pair from the theme. */
type Accent = "green" | "amber" | "blue" | "slate";

const ACCENTS: Record<Accent, { soft: string; ink: string }> = {
  green: { soft: cv("edr-soft"), ink: cv("edr-green.7") },
  amber: { soft: cv("edr-amber-soft"), ink: cv("edr-amber-text") },
  blue: { soft: cv("edr-blue-soft"), ink: cv("edr-blue") },
  slate: { soft: cv("edr-slate-soft"), ink: cv("edr-slate") },
};

interface StatKpiProps {
  icon: LucideIcon;
  label: string;
  value: string;
  delta: string;
  /** Color family for the icon chip. */
  accent: Accent;
  /** Tint of the delta pill — defaults to the card accent. */
  deltaTone?: Accent | "muted";
  /** Draw a separating border on the left (on wide layouts). */
  divider?: boolean;
  loading?: boolean;
}

export const StatKpi = memo(function StatKpi({
  icon: Icon,
  label,
  value,
  delta,
  accent,
  deltaTone,
  divider,
  loading,
}: StatKpiProps) {
  const a = ACCENTS[accent];
  const tone = deltaTone ?? accent;
  const pill =
    tone === "muted"
      ? { bg: cv("edr-slate-soft2"), fg: cv("edr-muted") }
      : { bg: ACCENTS[tone].soft, fg: ACCENTS[tone].ink };

  return (
    <Box
      className={
        divider
          ? "flex flex-col lg:border-l lg:border-edr-divider lg:pl-4"
          : "flex flex-col"
      }
    >
      {/* Icon chip + metric label, aligned on one line. */}
      <Group gap={12} wrap="nowrap" align="start">
        <Box
          className="flex size-10 shrink-0 items-center justify-center rounded-lg"
          style={{ background: a.soft }}
        >
          <Icon size={18} color={a.ink} strokeWidth={2} />
        </Box>
        <Box>
          <Box className="flex-row! flex items-end gap-2">
            <Text
              fz={24}
              fw={800}
              lh={1.1}
              c="edr-text"
              truncate
              className="tracking-tight"
            >
              {loading ? "—" : value}
            </Text>
            {delta && !loading && (
              <Box
                px={8}
                py={3}
                className="inline-flex w-fit rounded-full"
                style={{ background: pill.bg, maxWidth: "100%" }}
              >
                <Text fz={10} fw={700} lh={1.4} truncate style={{ color: pill.fg }}>
                  {delta}
                </Text>
              </Box>
            )}
          </Box>
          <Text fz={12} mt="xs" fw={600} c="edr-muted" truncate>
            {label}
          </Text>
        </Box>
      </Group>

      {/* Value + its trend pill, grouped together at the bottom of the cell. */}

    </Box>
  );
});
