import Link from "next/link";
import type { DepartmentHealth } from "@/lib/types";
import { cn } from "@/lib/utils";

type KPIStatCardProps = {
  data: DepartmentHealth;
  href?: string;
};

export default function KPIStatCard({ data, href }: KPIStatCardProps) {
  const content = (
    <>
      <div className="mb-3 flex items-start justify-between gap-3">
        <div className="min-w-0">
          <h3 className="text-h3 truncate font-semibold text-benell-text">{data.name}</h3>
          <p className="text-label text-benell-text-soft">{data.summary}</p>
        </div>
        <p
          className={cn(
            "text-kpi shrink-0 font-semibold",
            data.score >= 90 && "text-benell-green",
            data.score < 90 && data.score >= 80 && "text-benell-amber",
            data.score < 80 && "text-benell-red"
          )}
          aria-label={`Salud ${data.score} de 100`}
        >
          {data.score}
        </p>
      </div>

      <div className="space-y-2.5">
        {data.metrics.map((metric) => (
          <div key={metric.label} className="flex items-center justify-between gap-3 text-label">
            <span className="min-w-0 truncate text-benell-text-soft">{metric.label}</span>
            <div className="flex shrink-0 items-center gap-2 text-tabular">
              <span className="font-medium text-benell-text">{metric.value}</span>
              {metric.delta ? (
                <span className={cn("text-caption font-semibold", metric.positive ? "text-benell-green" : "text-benell-red")}>
                  {metric.positive ? "↗" : "↘"}
                  {metric.delta}
                </span>
              ) : null}
            </div>
          </div>
        ))}
      </div>
    </>
  );

  if (!href) {
    return <article className="rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell md:p-5">{content}</article>;
  }

  return (
    <Link
      href={href}
      className="group block rounded-benell border border-benell-stroke bg-benell-surface p-4 shadow-benell transition hover:border-benell-brown/60 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-benell-brown md:p-5"
    >
      {content}
      <p className="text-caption mt-3 font-semibold text-benell-brown transition group-hover:text-black">Ver KPIs del área →</p>
    </Link>
  );
}
