import { clsx } from "clsx";
import Link from "next/link";
import type { LucideIcon } from "lucide-react";

type Tone = "blue" | "emerald" | "red" | "amber" | "ink" | "slate";

const toneIconClasses: Record<Tone, string> = {
  blue: "text-[var(--color-blue)] bg-[var(--color-mist)]",
  emerald: "text-emerald-600 bg-emerald-50",
  red: "text-red-600 bg-red-50",
  amber: "text-amber-700 bg-amber-50",
  ink: "text-[var(--color-ink)] bg-[var(--color-line)]/60",
  slate: "text-[var(--color-slate)] bg-[var(--color-line)]/40",
};

type Props = {
  label: string;
  value: string | number;
  trend?: { label: string; tone?: "up" | "down" | "neutral" };
  Icon?: LucideIcon;
  tone?: Tone;
  href?: string;
  hint?: string;
  className?: string;
};

export function KpiCard({
  label,
  value,
  trend,
  Icon,
  tone = "blue",
  href,
  hint,
  className,
}: Props) {
  const body = (
    <div
      className={clsx(
        "group relative flex flex-col gap-3 rounded-xl border border-[var(--color-line)] bg-white p-5 transition-all",
        href &&
          "hover:-translate-y-0.5 hover:border-[var(--color-blue)] hover:shadow-sm",
        className,
      )}
    >
      <div className="flex items-center justify-between gap-3">
        <span className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
          {label}
        </span>
        {Icon && (
          <span
            className={clsx(
              "flex h-9 w-9 items-center justify-center rounded-lg",
              toneIconClasses[tone],
            )}
          >
            <Icon className="h-[18px] w-[18px]" aria-hidden />
          </span>
        )}
      </div>
      <div className="font-display text-[32px] font-extrabold leading-none tracking-tight text-[var(--color-ink)]">
        {value}
      </div>
      <div className="flex items-center justify-between gap-2">
        {trend ? (
          <span
            className={clsx(
              "text-[12px] font-semibold",
              trend.tone === "up" && "text-emerald-600",
              trend.tone === "down" && "text-red-600",
              (!trend.tone || trend.tone === "neutral") &&
                "text-[var(--color-slate)]",
            )}
          >
            {trend.label}
          </span>
        ) : hint ? (
          <span className="text-[12px] text-[var(--color-slate)]">{hint}</span>
        ) : (
          <span />
        )}
        {href && (
          <span className="text-[12px] font-semibold text-[var(--color-blue)] opacity-0 transition-opacity group-hover:opacity-100">
            View →
          </span>
        )}
      </div>
    </div>
  );

  if (href) {
    return (
      <Link href={href} className="block">
        {body}
      </Link>
    );
  }
  return body;
}
