"use client";

import { ReactNode } from "react";
import { TrendingUp, TrendingDown } from "lucide-react";
import { Spark } from "./Spark";

type SparkColor = "primary" | "cyan" | "green" | "pink" | "amber" | "red";

type KpiProps = {
  title: ReactNode;
  value: ReactNode;
  /** Optional subtitle line under the number (e.g., "이번 달") */
  sub?: ReactNode;
  /** +12 / -3 etc. — green up-pill or red down-pill rendered automatically. */
  delta?: number;
  /** Color of the BIG number. Default = text color. */
  color?: "default" | "cyan" | "green" | "pink" | "amber";
  /** Sparkline data to render under the number (small inline trend). */
  spark?: number[];
  sparkColor?: SparkColor;
  /** Add primary glow shadow to the card. */
  glow?: boolean;
  className?: string;
};

const NUM_COLOR_CLASS: Record<NonNullable<KpiProps["color"]>, string> = {
  default: "",
  cyan: "kpi-cyan",
  green: "kpi-green",
  pink: "kpi-pink",
  amber: "kpi-amber",
};

export function Kpi({
  title,
  value,
  sub,
  delta,
  color = "default",
  spark,
  sparkColor,
  glow = false,
  className = "",
}: KpiProps) {
  const showDelta = typeof delta === "number" && delta !== 0;
  const isUp = (delta ?? 0) > 0;
  const cardCls = `v5-card ${glow ? "glow" : ""} ${className}`.trim();

  return (
    <div className={cardCls}>
      <div className="v5-card-head">
        <div className="v5-card-title">{title}</div>
      </div>
      <div className={`v5-kpi-num ${NUM_COLOR_CLASS[color]}`.trim()}>
        <span>{value}</span>
        {showDelta && (
          <span className={`v5-kpi-delta ${isUp ? "up" : "down"}`}>
            {isUp ? <TrendingUp /> : <TrendingDown />}
            {Math.abs(delta!)}
          </span>
        )}
      </div>
      {sub && <div className="v5-kpi-sub">{sub}</div>}
      {spark && spark.length > 0 && (
        <div style={{ marginTop: ".4rem" }}>
          <Spark values={spark} color={sparkColor ?? (color === "default" ? "primary" : (color as SparkColor))} />
        </div>
      )}
    </div>
  );
}
