import { useId, useState, type ReactNode } from "react";
import {
  Area,
  AreaChart,
  CartesianGrid,
  ReferenceLine,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import type { Slice } from "@/api/public";
import { fmtInt, fmtPct } from "@/lib/format";
import { cn } from "@/lib/utils";

/** Checked for colour-blind readers and contrast on white. */
export const BLUE = "#00809e";
export const OCHRE = "#cf7a00";
const share = (v: number, all: number) => (all ? fmtPct((v / all) * 100) : "—");

/** A chart with its title, a note and the same numbers as a table. */
export function Figure({
  title,
  note,
  head = ["Group", "Trainees"],
  rows,
  children,
  className,
}: {
  title: string;
  note?: ReactNode;
  head?: string[];
  rows: (string | number)[][];
  children: ReactNode;
  className?: string;
}) {
  const [table, setTable] = useState(false);
  const id = useId();
  return (
    <figure className={cn("flex min-w-0 flex-col rounded-xl border bg-card p-5", className)}>
      <div className="flex items-start justify-between gap-3">
        <figcaption id={id} className="font-display text-[16px] font-semibold leading-snug">
          {title}
        </figcaption>
        <button
          type="button"
          className="shrink-0 rounded px-2 py-1 text-[12.5px] text-primary underline underline-offset-2 hover:bg-primary-soft"
          aria-pressed={table}
          onClick={() => setTable(!table)}
        >
          {table ? "Show chart" : "Show table"}
        </button>
      </div>
      <div className="mt-4 flex-1">
        {table ? (
          <div className="max-h-80 overflow-auto">
            <table className="w-full text-[13px] tabular" aria-labelledby={id}>
              <thead>
                <tr className="border-b text-left text-muted-foreground">
                  {head.map((h, i) => (
                    <th key={h} scope="col" className={cn("py-1.5 font-medium", i && "text-right")}>
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {rows.map((r) => (
                  <tr key={String(r[0])} className="border-b last:border-0">
                    {r.map((c, i) => (
                      <td key={i} className={cn("py-1.5", i && "text-right")}>
                        {typeof c === "number" ? fmtInt(c) : c}
                      </td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          children
        )}
      </div>
      {note && <p className="mt-4 text-[12.5px] leading-5 text-muted-foreground">{note}</p>}
    </figure>
  );
}
/** Horizontal bars for one measure. Every bar carries its number, so nothing depends on colour. */
export function Bars({ rows, total }: { rows: Slice[]; total?: number }) {
  const max = Math.max(1, ...rows.map((r) => r.value));
  const all = total ?? rows.reduce((a, r) => a + r.value, 0);
  return (
    <ul className="space-y-3">
      {rows.map((r) => (
        <li
          key={r.label}
          className="group"
          title={`${r.label}: ${fmtInt(r.value)} (${share(r.value, all)})`}
        >
          <div className="flex items-baseline justify-between gap-3 text-[13px]">
            <span>{r.label}</span>
            <span className="tabular">
              <b className="font-semibold">{fmtInt(r.value)}</b>{" "}
              <span className="inline-block w-14 text-right text-muted-foreground">
                {share(r.value, all)}
              </span>
            </span>
          </div>
          <div className="mt-1 h-2.5 rounded-r bg-surface-2">
            <div
              className="h-full rounded-r transition-opacity group-hover:opacity-80"
              style={{
                width: `${(r.value / max) * 100}%`,
                background: r.label === "Other" ? "var(--subtle)" : BLUE,
              }}
            />
          </div>
        </li>
      ))}
    </ul>
  );
}
/** Two parts of a whole, in one bar. */
export function Split({ a, b }: { a: Slice; b: Slice }) {
  const all = a.value + b.value;
  return (
    <div>
      <div className="flex justify-between gap-4">
        {[a, b].map((x, i) => (
          <div key={x.label} className={i ? "text-right" : ""}>
            <p className="font-display text-3xl font-bold tabular">{share(x.value, all)}</p>
            <p className={cn("flex items-center gap-2 text-[13px]", i && "justify-end")}>
              <span className="h-2.5 w-2.5 rounded-sm" style={{ background: i ? BLUE : OCHRE }} />
              {x.label}, {fmtInt(x.value)}
            </p>
          </div>
        ))}
      </div>
      <div className="mt-4 flex h-5 gap-0.5 overflow-hidden rounded">
        <div
          style={{ width: `${(a.value / all) * 100}%`, background: OCHRE }}
          title={`${a.label}: ${fmtInt(a.value)}`}
        />
        <div
          className="flex-1"
          style={{ background: BLUE }}
          title={`${b.label}: ${fmtInt(b.value)}`}
        />
      </div>
    </div>
  );
}
/** Columns for ordered groups, such as ages. */
export function Columns({ rows }: { rows: Slice[] }) {
  const max = Math.max(1, ...rows.map((r) => r.value));
  const all = rows.reduce((a, r) => a + r.value, 0);
  return (
    <div className="flex h-60 items-end lg:h-92">
      {rows.map((r) => (
        <div
          key={r.label}
          className="group flex h-full flex-1 flex-col justify-end text-center"
          title={`${r.label}: ${fmtInt(r.value)} (${share(r.value, all)})`}
        >
          <span className="text-[13px] font-semibold tabular">{fmtInt(r.value)}</span>
          <div
            className="mx-auto mt-1 w-full max-w-14 rounded-t transition-opacity group-hover:opacity-80"
            style={{ height: `${(r.value / max) * 72}%`, background: BLUE }}
          />
          <span className="border-t py-1.5 text-[13px] text-muted-foreground">{r.label}</span>
        </div>
      ))}
    </div>
  );
}
export interface Point {
  label: string;
  value: number;
}
/** One line over time. The line shows the exact value under the pointer. */
export function Trend({
  rows,
  pct,
  from,
  target,
  height = 260,
  name,
}: {
  rows: Point[];
  pct?: boolean;
  from?: number;
  target?: { value: number; label: string } | undefined;
  height?: number;
  name: string;
}) {
  const id = useId().replace(/:/g, "");
  const f = (v: number) => (pct ? fmtPct(v) : fmtInt(v));
  return (
    <ResponsiveContainer width="100%" height={height}>
      <AreaChart data={rows} margin={{ top: 18, right: 12, bottom: 0, left: 0 }} accessibilityLayer>
        <defs>
          <linearGradient id={id} x1="0" x2="0" y1="0" y2="1">
            <stop offset="0" stopColor={BLUE} stopOpacity={0.22} />
            <stop offset="1" stopColor={BLUE} stopOpacity={0.02} />
          </linearGradient>
        </defs>
        <CartesianGrid vertical={false} stroke="var(--border)" />
        <XAxis
          dataKey="label"
          tickLine={false}
          axisLine={false}
          minTickGap={28}
          tick={{ fontSize: 12, fill: "var(--muted-foreground)" }}
        />
        <YAxis
          width={52}
          domain={[from ?? 0, pct ? 100 : "auto"]}
          tickLine={false}
          axisLine={false}
          tickFormatter={(v: number) => (pct ? `${v} %` : fmtInt(v))}
          tick={{ fontSize: 12, fill: "var(--muted-foreground)" }}
        />
        <Tooltip
          cursor={{ stroke: "var(--muted-foreground)", strokeDasharray: "3 3" }}
          content={({ active, payload }) => {
            const p = payload?.[0]?.payload as Point | undefined;
            return active && p ? (
              <div className="rounded-lg border bg-popover px-3 py-2 text-[13px] shadow-(--shadow-card)">
                <p className="text-muted-foreground">{p.label}</p>
                <p className="font-semibold tabular">
                  {f(p.value)} <span className="font-normal">{name}</span>
                </p>
              </div>
            ) : null;
          }}
        />
        {target && (
          <ReferenceLine
            y={target.value}
            stroke="var(--foreground)"
            strokeDasharray="5 4"
            label={{
              value: target.label,
              position: "insideBottomRight",
              fontSize: 12,
              fill: "var(--foreground)",
            }}
          />
        )}
        <Area
          type="monotone"
          dataKey="value"
          stroke={BLUE}
          strokeWidth={2}
          fill={`url(#${id})`}
          isAnimationActive={false}
          activeDot={{ r: 5, stroke: "var(--card)", strokeWidth: 2 }}
        />
      </AreaChart>
    </ResponsiveContainer>
  );
}
/** The way from enrolment to a job. Steps nobody has reported yet are shown as open, never as zero. */
export function Journey({ rows }: { rows: { label: string; value?: number }[] }) {
  const all = rows[0]?.value ?? 1;
  return (
    <ol className="space-y-2">
      {rows.map((r) => (
        <li key={r.label} className="grid items-center gap-x-4 gap-y-1 sm:grid-cols-[13rem_1fr]">
          <span className="text-[14px]">{r.label}</span>
          {r.value === undefined ? (
            <div className="flex h-10 items-center rounded border border-dashed px-3 text-[13px] text-muted-foreground">
              Not reported yet
            </div>
          ) : (
            <div
              className="grid h-10 grid-cols-[1fr_8.5rem] items-center rounded bg-surface-2"
              title={`${r.label}: ${fmtInt(r.value)} (${share(r.value, all)})`}
            >
              <div
                className="h-full rounded-l rounded-r-md"
                style={{ width: `${Math.max(2, (r.value / all) * 100)}%`, background: BLUE }}
              />
              <span className="whitespace-nowrap pl-3 text-[14px] tabular">
                <b className="font-semibold">{fmtInt(r.value)}</b>{" "}
                <span className="text-muted-foreground">{share(r.value, all)}</span>
              </span>
            </div>
          )}
        </li>
      ))}
    </ol>
  );
}
/** A result next to the programme's general target. */
export function Bullet({
  value,
  target,
}: {
  value: number | undefined;
  target: number | undefined;
}) {
  return (
    <div className="relative h-3 rounded-r bg-surface-2">
      {value !== undefined && (
        <div
          className="h-full rounded-r"
          style={{ width: `${Math.min(100, value)}%`, background: BLUE }}
        />
      )}
      {target !== undefined && (
        <span
          className="absolute -top-1 h-5 w-0.5 bg-foreground"
          style={{ left: `calc(${Math.min(100, target)}% - 2px)` }}
          aria-hidden="true"
        />
      )}
    </div>
  );
}
