import { Card } from "@/components/ui/card";
import { AnimatedCounter } from "@/components/ui/animated-counter";
import { cn } from "@/lib/utils";
import type { KPISet } from "@/lib/types";

type MetricKey =
  | "emails_sent"
  | "opened"
  | "total_opens"
  | "clicked"
  | "total_clicks"
  | "ctor";

export function KpiHighlights({ kpis, className }: { kpis: KPISet; className?: string }) {
  return (
    <section className={cn("grid w-full gap-2.5 xl:grid-cols-2", className)}>
      <Card className="enter-fade-up min-h-[116px] border-[#db822c] !bg-[linear-gradient(155deg,#f7a043_0%,#f28f32_56%,#e58124_100%)] p-3 text-white shadow-[0_20px_32px_-22px_rgba(189,101,26,0.9)] transition duration-300 hover:-translate-y-0.5 hover:shadow-[0_26px_40px_-26px_rgba(189,101,26,0.95)]">
        <p className="caption text-[10px] uppercase tracking-[0.2em] text-white">Emails Sent</p>
        <p className="mt-1 text-[58px] font-black leading-[0.85] tracking-tight text-white">
          <AnimatedCounter value={kpis.total_emails_sent} />
        </p>
      </Card>

      <Card
        className="enter-fade-up min-h-[116px] border-[#d8e4f3] bg-[linear-gradient(150deg,#ffffff_0%,#f2f8ff_100%)] p-3 transition duration-300 hover:-translate-y-0.5 hover:border-[#c8dbef]"
        style={{ ["--enter-delay" as string]: "60ms" }}
      >
        <p className="caption text-[10px] uppercase tracking-[0.2em] text-slate-500">Opened</p>
        <div className="mt-1 flex flex-wrap items-end gap-x-3 gap-y-1">
          <p className="min-w-0 text-[58px] font-black leading-[0.85] tracking-tight text-slate-900">
            <AnimatedCounter value={kpis.total_opened} />
          </p>
          <p className="mb-1 inline-flex shrink-0 whitespace-nowrap rounded-full bg-[#fff4e8] px-2 py-0.5 text-sm font-semibold text-[#d9852c]">
            <AnimatedCounter
              value={kpis.open_rate * 100}
              format="decimal"
              decimals={1}
              suffix="%"
              durationMs={700}
            />
          </p>
        </div>
      </Card>
    </section>
  );
}

export function KpiCards({ kpis }: { kpis: KPISet }) {
  const cards = [
    { label: "Total Opens", value: kpis.total_opens, accent: "#2663AC", isPercent: false },
    {
      label: "Clicked",
      value: kpis.total_clicked,
      sub: kpis.ctr,
      accent: "#F7993A",
      badgeClassName: "bg-[#fff4e8] text-[#d9852c]",
      isPercent: false,
    },
    { label: "Total Clicks", value: kpis.total_clicks, accent: "#2663AC", isPercent: false },
    { label: "Click To Open %", value: kpis.ctor, accent: "#F7993A", isPercent: true },
  ];

  return (
    <section className="grid gap-2.5 sm:grid-cols-2 xl:grid-cols-4">
      {cards.map((card, index) => (
        <Card
          key={card.label}
          className="enter-fade-up group relative min-h-[102px] overflow-hidden border-[#d8e4f3] bg-[linear-gradient(145deg,#ffffff_0%,#f6fbff_82%)] p-3 transition duration-300 hover:-translate-y-0.5 hover:border-[#c8dbef]"
          style={{ ["--enter-delay" as string]: `${120 + index * 40}ms` }}
        >
          <div
            className="pointer-events-none absolute -right-10 -top-10 h-20 w-20 rounded-full opacity-20 blur-2xl"
            style={{ backgroundColor: card.accent }}
          />
          <div className="absolute left-0 top-0 h-1 w-full" style={{ backgroundColor: card.accent }} />
          <p className="caption text-[10px] uppercase tracking-[0.18em] text-slate-500">{card.label}</p>
          {card.sub !== undefined ? (
            <div className="mt-1 flex flex-wrap items-end gap-x-3 gap-y-1">
              <p className="min-w-0 text-[52px] font-black leading-[0.86] tracking-tight text-slate-900">
                <AnimatedCounter
                  value={card.isPercent ? card.value * 100 : card.value}
                  durationMs={760}
                  format={card.isPercent ? "decimal" : "integer"}
                  decimals={card.isPercent ? 1 : 0}
                  suffix={card.isPercent ? "%" : ""}
                />
              </p>
              <p
                className={cn(
                  "mb-1 inline-flex shrink-0 whitespace-nowrap rounded-full px-2 py-0.5 text-sm font-semibold",
                  card.badgeClassName,
                )}
              >
                <AnimatedCounter
                  value={card.sub * 100}
                  format="decimal"
                  decimals={1}
                  suffix="%"
                  durationMs={640}
                />
              </p>
            </div>
          ) : (
            <p className="mt-1 text-[52px] font-black leading-[0.86] tracking-tight text-slate-900">
              <AnimatedCounter
                value={card.isPercent ? card.value * 100 : card.value}
                durationMs={760}
                format={card.isPercent ? "decimal" : "integer"}
                decimals={card.isPercent ? 1 : 0}
                suffix={card.isPercent ? "%" : ""}
              />
            </p>
          )}
        </Card>
      ))}
    </section>
  );
}

export function KpiRow({
  kpis,
  activeMetric,
  onMetricSelect,
}: {
  kpis: KPISet;
  activeMetric?: MetricKey | null;
  onMetricSelect?: (metric: MetricKey) => void;
}) {
  function cardClass(metric: MetricKey) {
    return activeMetric === metric
      ? "ring-2 ring-[#2663AC]/25 border-[#bfd4ea] shadow-[0_0_0_4px_rgba(38,99,172,0.08)]"
      : "hover:ring-2 hover:ring-[#2663AC]/12 hover:shadow-[0_0_0_4px_rgba(38,99,172,0.04)]";
  }

  function MetricIndicator({ metric, isOrange }: { metric: MetricKey; isOrange: boolean }) {
    const active = activeMetric === metric;
    const chromeClass = isOrange
      ? active
        ? "border-white/50 bg-white/22 text-white"
        : "border-white/28 bg-white/10 text-white/78"
      : active
        ? "border-[#bfd4ea] bg-[#edf5ff] text-[#2663AC]"
        : "border-[#d8e4f3] bg-white/92 text-slate-400";

    return (
      <div
        className={cn(
          "absolute right-3 top-3 flex h-8 w-8 items-center justify-center rounded-full border transition duration-300",
          chromeClass,
        )}
        aria-hidden="true"
      >
        {active ? (
          <svg viewBox="0 0 20 20" className="h-4 w-4 fill-current">
            <path d="M5 9.25h10a.75.75 0 0 1 0 1.5H5a.75.75 0 0 1 0-1.5Z" />
          </svg>
        ) : (
          <svg viewBox="0 0 20 20" className="h-4 w-4 fill-current">
            <path d="M4.75 13.5a.75.75 0 0 1-.75-.75V11a.75.75 0 0 1 1.5 0v1.75a.75.75 0 0 1-.75.75Zm5.25 0a.75.75 0 0 1-.75-.75V7.5a.75.75 0 0 1 1.5 0v5.25a.75.75 0 0 1-.75.75Zm5.25 0a.75.75 0 0 1-.75-.75V9.25a.75.75 0 0 1 1.5 0v3.5a.75.75 0 0 1-.75.75Z" />
          </svg>
        )}
      </div>
    );
  }

  const pillItems = [
    {
      key: "emails_sent" as MetricKey,
      label: "Emails Sent",
      isOrange: true,
      accent: "#F7993A",
      delay: "0ms",
      render: () => (
        <p className="mt-auto text-[38px] font-black leading-[0.9] tracking-tight text-white xl:text-[42px]">
          <AnimatedCounter value={kpis.total_emails_sent} />
        </p>
      ),
    },
    {
      key: "opened" as MetricKey,
      label: "Opened",
      isOrange: false,
      accent: "#2663AC",
      delay: "40ms",
      render: () => (
        <div className="mt-auto flex flex-wrap items-end gap-x-2 gap-y-1">
          <p className="min-w-0 text-[38px] font-black leading-[0.9] tracking-tight text-slate-900 xl:text-[42px]">
            <AnimatedCounter value={kpis.total_opened} />
          </p>
          <p className="mb-0.5 inline-flex shrink-0 whitespace-nowrap rounded-full bg-[#fff4e8] px-2 py-0.5 text-xs font-semibold text-[#d9852c]">
            <AnimatedCounter value={kpis.open_rate * 100} format="decimal" decimals={1} suffix="%" durationMs={700} />
          </p>
        </div>
      ),
    },
    {
      key: "total_opens" as MetricKey,
      label: "Total Opens",
      isOrange: false,
      accent: "#2663AC",
      delay: "80ms",
      render: () => (
        <p className="mt-auto text-[38px] font-black leading-[0.9] tracking-tight text-slate-900 xl:text-[42px]">
          <AnimatedCounter value={kpis.total_opens} />
        </p>
      ),
    },
    {
      key: "clicked" as MetricKey,
      label: "Clicked",
      isOrange: false,
      accent: "#F7993A",
      delay: "120ms",
      render: () => (
        <div className="mt-auto flex flex-wrap items-end gap-x-2 gap-y-1">
          <p className="min-w-0 text-[38px] font-black leading-[0.9] tracking-tight text-slate-900 xl:text-[42px]">
            <AnimatedCounter value={kpis.total_clicked} />
          </p>
          <p className="mb-0.5 inline-flex shrink-0 whitespace-nowrap rounded-full bg-[#fff4e8] px-2 py-0.5 text-xs font-semibold text-[#d9852c]">
            <AnimatedCounter value={kpis.ctr * 100} format="decimal" decimals={1} suffix="%" durationMs={640} />
          </p>
        </div>
      ),
    },
    {
      key: "total_clicks" as MetricKey,
      label: "Total Clicks",
      isOrange: false,
      accent: "#2663AC",
      delay: "160ms",
      render: () => (
        <p className="mt-auto text-[38px] font-black leading-[0.9] tracking-tight text-slate-900 xl:text-[42px]">
          <AnimatedCounter value={kpis.total_clicks} />
        </p>
      ),
    },
    {
      key: "ctor" as MetricKey,
      label: "Click To Open %",
      isOrange: false,
      accent: "#F7993A",
      delay: "200ms",
      render: () => (
        <p className="mt-auto text-[38px] font-black leading-[0.9] tracking-tight text-slate-900 xl:text-[42px]">
          <AnimatedCounter value={kpis.ctor * 100} format="decimal" decimals={1} suffix="%" durationMs={760} />
        </p>
      ),
    },
  ];

  return (
    <section className="grid gap-2.5 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-6">
      {pillItems.map((item) => (
        <button
          key={item.key}
          type="button"
          onClick={() => onMetricSelect?.(item.key)}
          aria-pressed={activeMetric === item.key}
          className="h-[112px] cursor-pointer rounded-[24px] text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#2663AC]/50 focus-visible:ring-offset-2"
          style={{ ["--enter-delay" as string]: item.delay }}
        >
          <Card
            className={cn(
              "enter-fade-up relative flex h-full flex-col overflow-hidden p-3 transition duration-300 hover:-translate-y-0.5",
              item.isOrange
                ? "border-[#db822c] !bg-[linear-gradient(155deg,#f7a043_0%,#f28f32_56%,#e58124_100%)] text-white shadow-[0_20px_32px_-22px_rgba(189,101,26,0.9)] hover:shadow-[0_26px_40px_-26px_rgba(189,101,26,0.95)]"
                : "border-[#d8e4f3] bg-[linear-gradient(145deg,#ffffff_0%,#f6fbff_82%)] hover:border-[#c8dbef]",
              cardClass(item.key),
            )}
          >
            <MetricIndicator metric={item.key} isOrange={item.isOrange} />
            {!item.isOrange && (
              <>
                <div
                  className="pointer-events-none absolute -right-10 -top-10 h-20 w-20 rounded-full opacity-20 blur-2xl"
                  style={{ backgroundColor: item.accent }}
                />
                <div className="absolute left-0 top-0 h-1 w-full" style={{ backgroundColor: item.accent }} />
              </>
            )}
            <p className={cn("caption text-[10px] uppercase tracking-[0.2em]", item.isOrange ? "text-white" : "text-slate-500")}>
              {item.label}
            </p>
            {item.render()}
          </Card>
        </button>
      ))}
    </section>
  );
}
