import { Link } from "@tanstack/react-router";
import { ShieldCheck } from "lucide-react";
import { Line, LineChart, ResponsiveContainer } from "recharts";
import { StatusBadge } from "./status-badge";
import { fmtInt, fmtPct, fmtTime } from "@/lib/format";
import type { KpiCardData } from "@/api/programme";
import { cn } from "@/lib/utils";

export function TargetBar({
  value,
  target,
  comparator = ">=",
  max,
  showLabels = false,
}: {
  value?: number | undefined;
  target?: number | undefined;
  comparator?: ">=" | "<=";
  max?: number;
  showLabels?: boolean;
}) {
  const m = max ?? Math.max(100, (target ?? 0) * 1.15, value ?? 0);
  const ok =
    value !== undefined &&
    target !== undefined &&
    (comparator === ">=" ? value >= target : value <= target);
  return (
    <div>
      <div className="relative h-1.5 w-full rounded-full bg-surface-2">
        {value !== undefined && (
          <div
            className={cn("h-full rounded-full", ok ? "bg-success" : "bg-primary")}
            style={{ width: `${Math.min(100, (value / m) * 100)}%` }}
          />
        )}
        {target !== undefined && (
          <div
            className="absolute -top-1 h-3.5 w-0.5 rounded bg-amber"
            style={{ left: `${Math.min(100, (target / m) * 100)}%` }}
            aria-hidden="true"
          />
        )}
      </div>
      {showLabels && (
        <p className="mt-1 text-[12px] text-muted-foreground">
          {fmtPct(value)} vs target {fmtPct(target)}
        </p>
      )}
    </div>
  );
}
export function Sparkline({ data }: { data: { value: number }[] }) {
  if (data.length < 2) return null;
  return (
    <div className="h-8 w-20" aria-hidden="true">
      <ResponsiveContainer>
        <LineChart data={data}>
          <Line
            type="monotone"
            dataKey="value"
            stroke="var(--primary)"
            strokeWidth={1.5}
            dot={false}
            isAnimationActive={false}
          />
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
}
export function ProgressRing({
  value,
  size = 44,
  label,
}: {
  value: number;
  size?: number;
  label?: string;
}) {
  const r = size / 2 - 4;
  const c = 2 * Math.PI * r;
  return (
    <div
      className="relative inline-flex items-center justify-center"
      style={{ width: size, height: size }}
      role="img"
      aria-label={label ?? `${Math.round(value)} %`}
    >
      <svg width={size} height={size} className="-rotate-90">
        <circle
          cx={size / 2}
          cy={size / 2}
          r={r}
          fill="none"
          stroke="var(--surface-2)"
          strokeWidth="4"
        />
        <circle
          cx={size / 2}
          cy={size / 2}
          r={r}
          fill="none"
          stroke="var(--primary)"
          strokeWidth="4"
          strokeDasharray={c}
          strokeDashoffset={c * (1 - Math.min(100, value) / 100)}
          strokeLinecap="round"
        />
      </svg>
      <span className="absolute text-[11px] font-semibold tabular">{Math.round(value)}%</span>
    </div>
  );
}
export function KpiCard({ k, href }: { k: KpiCardData; href?: string }) {
  const fmt = (v?: number) => (k.unit === "%" ? fmtPct(v) : fmtInt(v));
  const delta =
    k.value !== undefined && k.previous !== undefined ? k.value - k.previous : undefined;
  const good = delta !== undefined && (k.direction === "lower_is_better" ? delta <= 0 : delta >= 0);
  const body = (
    <div className="flex h-full flex-col rounded-xl border bg-card p-4 shadow-(--shadow-card) transition-colors hover:border-primary/40">
      <div className="flex items-start justify-between gap-2">
        <p className="text-[12.5px] font-medium text-muted-foreground">{k.name}</p>
        <StatusBadge status={k.status} />
      </div>
      <div className="mt-2 flex items-end justify-between gap-2">
        <div>
          <span className="font-display text-[28px] font-bold leading-8 tabular">
            {fmt(k.value)}
          </span>
          {delta !== undefined && Math.abs(delta) > 0.05 && (
            <span
              className={cn("ml-2 text-[12px] font-medium", good ? "text-success" : "text-danger")}
            >
              {delta > 0 ? "▲" : "▼"}{" "}
              {k.unit === "%" ? Math.abs(delta).toFixed(1) : fmtInt(Math.abs(delta))}
            </span>
          )}
        </div>
        <Sparkline data={k.trend} />
      </div>
      {k.numerator !== undefined && k.denominator !== undefined && k.denominatorLabel && (
        <p className="mt-1 text-[12px] text-muted-foreground">
          {fmtInt(k.numerator)} of {fmtInt(k.denominator)} ({k.denominatorLabel.toLowerCase()})
        </p>
      )}
      {k.verified !== undefined && (
        <p className="mt-1 flex items-center gap-1 text-[12px] font-medium text-success">
          <ShieldCheck className="h-3.5 w-3.5" /> Verified {fmt(k.verified)}
        </p>
      )}
      <div className="mt-3">
        <TargetBar
          value={k.value}
          target={k.target}
          comparator={k.direction === "lower_is_better" ? "<=" : ">="}
          {...(k.unit === "#" && k.target ? { max: k.target * 1.2 } : {})}
        />
      </div>
      <p className="mt-2 text-[12px] text-muted-foreground">
        {k.target === undefined
          ? "No target set"
          : `Target ${k.direction === "lower_is_better" ? "≤" : "≥"} ${fmt(k.target)}`}{" "}
        · as of {fmtTime(k.computedAt)}
      </p>
    </div>
  );
  return href ? (
    <Link to={href} className="block rounded-xl">
      {body}
    </Link>
  ) : (
    body
  );
}
