import type { ReactNode } from "react";
import { Button } from "@/components/ui/button";
import { Bars, Bullet, Columns, Figure, Journey, Split, Trend } from "@/components/public/charts";
import type { PublicStats, Slice } from "@/api/public";
import { fmtInt, fmtPct } from "@/lib/format";

const rows = (s: Slice[]) => s.map((x): [string, number] => [x.label, x.value]);
const mon = (m: string) =>
  new Date(`${m}-01T00:00:00Z`).toLocaleDateString("en-GB", {
    month: "short",
    year: "numeric",
    timeZone: "UTC",
  });
const day = (w: string) =>
  new Date(`${w.slice(0, 10)}T00:00:00Z`).toLocaleDateString("en-GB", {
    day: "numeric",
    month: "short",
    timeZone: "UTC",
  });
const NAMES: Record<string, string> = {
  eligible_enrolled_trainee_rate: "Eligible trainees enrolled",
  trainee_attendance_rate: "Attendance",
  trainee_dropout_rate: "Dropout",
  training_completion_rate: "Training completion",
  training_certification_rate: "Certification",
  employment_placement_rate: "Employment placement",
  job_retention_3_month_rate: "Job retention after 3 months",
  locality_compliant_placement_rate: "Placement in an eligible locality",
};
function download(d: PublicStats) {
  const out: (string | number)[][] = [["Section", "Item", "Value"]];
  for (const j of d.journey) out.push(["Trainee journey", j.label, j.value ?? "not reported yet"]);
  for (const r of d.results)
    out.push(["Indicator result (%)", NAMES[r.code] ?? r.name, r.value ?? "not reported yet"]);
  for (const e of d.enrolment) out.push(["Enrolled in month", e.month, e.value]);
  for (const a of d.attendance)
    out.push(["Attendance rate of the week (%)", a.week.slice(0, 10), a.value]);
  out.push(["Sex", "Women", d.female], ["Sex", "Men", d.male]);
  const groups: [string, Slice[]][] = [
    ["Age", d.age],
    ["Education", d.education],
    ["Work before training", d.employment],
    ["Region of origin", d.regions],
    ["Training city", d.locations],
    ["Level", d.levels],
    ["Field", d.fields],
    ["Inclusion", d.inclusion],
    ["Feedback", d.feedback.byCategory],
  ];
  for (const [n, s] of groups) for (const x of s) out.push([n, x.label, x.value]);
  const csv = `\uFEFF${out.map((r) => r.map((c) => `"${String(c).replace(/"/g, '""')}"`).join(",")).join("\r\n")}`;
  const a = document.createElement("a");
  a.href = URL.createObjectURL(new Blob([csv], { type: "text/csv" }));
  a.download = `pbps_public_data_${d.asOf.slice(0, 10)}.csv`;
  a.click();
  setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}
function Block({
  id,
  title,
  intro,
  tone,
  children,
}: {
  id: string;
  title: string;
  intro: ReactNode;
  tone?: boolean;
  children: ReactNode;
}) {
  return (
    <section id={id} className={`scroll-mt-16 ${tone ? "border-y bg-surface-2/60" : ""}`}>
      <div className="mx-auto max-w-6xl px-6 py-16 sm:py-20">
        <h2 className="max-w-3xl text-balance font-display text-3xl font-bold leading-tight tracking-tight sm:text-4xl">
          {title}
        </h2>
        <p className="mt-4 max-w-[68ch] text-muted-foreground">{intro}</p>
        <div className="mt-10">{children}</div>
      </div>
    </section>
  );
}
export default function Evidence({ d }: { d: PublicStats }) {
  const scale: [string, number][] = [
    ["training providers under contract", d.providers],
    ["training programmes", d.trainings],
    ["training sites", d.sites],
    ["classes", d.classes.total],
    ["classes finished", d.classes.ended],
    ["class days recorded", d.sessions],
    ["attendance marks", d.marks],
    ["outcome reports accepted", d.reports],
  ];
  const known = d.results.filter((r) => r.value !== undefined);
  const later = d.results.filter((r) => r.value === undefined);
  const att = d.results.find((r) => r.code === "trainee_attendance_rate");
  return (
    <>
      <Block
        id="results"
        tone
        title="Results to date"
        intro="Reported results of the whole programme, compared with its general targets. They are claims by the providers until independent verification is finished."
      >
        <div className="rounded-xl border bg-card">
          <div className="hidden grid-cols-[14rem_1fr_7rem_7rem] gap-5 border-b px-5 py-3 text-[13px] text-muted-foreground md:grid">
            <span>Indicator</span>
            <span>Reported result. The black line marks the general target.</span>
            <span className="text-right">Reported</span>
            <span className="text-right">Verified</span>
          </div>
          <ul className="divide-y">
            {known.map((r) => (
              <li
                key={r.code}
                className="grid gap-x-5 gap-y-2 px-5 py-4 md:grid-cols-[14rem_1fr_7rem_7rem] md:items-center"
              >
                <span className="font-semibold">{NAMES[r.code] ?? r.name}</span>
                <div>
                  <Bullet value={r.value} target={r.target} />
                  <p className="mt-1.5 text-[13px] text-muted-foreground">
                    {fmtInt(r.numerator)} of {fmtInt(r.denominator)}
                    {r.denominatorLabel && ` (${r.denominatorLabel.toLowerCase()})`}
                    {r.target !== undefined &&
                      `, target ${r.lowerBetter ? "at most" : "at least"} ${fmtPct(r.target)}`}
                    {r.lowerBetter &&
                      ". Lower is better; places above the contracted number are not counted"}
                  </p>
                </div>
                <span className="font-display text-2xl font-bold tabular md:text-right">
                  {fmtPct(r.value)}
                </span>
                <span className="text-[14px] text-muted-foreground md:text-right">
                  <span className="md:hidden">Verified: </span>
                  {r.verified === undefined ? "Not yet" : fmtPct(r.verified)}
                </span>
              </li>
            ))}
          </ul>
          {later.length > 0 && (
            <p className="border-t px-5 py-4 text-[14px] text-muted-foreground">
              Not reported yet, because they follow the end of training:{" "}
              {later.map((r) => (NAMES[r.code] ?? r.name).toLowerCase()).join(", ")}.
            </p>
          )}
        </div>
        <dl className="mt-10 grid grid-cols-2 gap-x-8 gap-y-7 md:grid-cols-4">
          {scale.map(([l, v]) => (
            <div key={l} className="flex flex-col-reverse justify-end border-t pt-3">
              <dt className="text-[14px] text-muted-foreground">{l}</dt>
              <dd className="font-display text-3xl font-bold tabular">{fmtInt(v)}</dd>
            </div>
          ))}
        </dl>
        <Figure
          className="mt-10"
          title="From enrolment to employment"
          head={["Step", "Trainees"]}
          rows={d.journey.map((j) => [j.label, j.value ?? "not reported yet"])}
          note={`Share of all ${fmtInt(d.trainees)} enrolled trainees. ${fmtInt(d.classes.running)} of ${fmtInt(d.classes.total)} classes are still running and reports follow in stages, so later steps will grow.`}
        >
          <Journey rows={d.journey} />
        </Figure>
        <div className="mt-5 grid gap-5 lg:grid-cols-2">
          <Figure
            title="Trainees enrolled, cumulative"
            head={["Month", "Enrolled", "Total"]}
            rows={d.enrolment.map((e) => [mon(e.month), e.value, e.total])}
            note="By the month in which the trainee was registered in the system."
          >
            <Trend
              name="enrolled"
              rows={d.enrolment.map((e) => ({ label: mon(e.month), value: e.total }))}
            />
          </Figure>
          <Figure
            title="Weekly attendance rate"
            head={["Week of", "Rate"]}
            rows={d.attendance.map((a) => [day(a.week), fmtPct(a.value)])}
            note="Share of recorded marks that were present. Weeks with fewer than 200 marks are left out. The axis starts at 60 %."
          >
            <Trend
              name="present"
              pct
              from={60}
              rows={d.attendance.map((a) => ({ label: day(a.week), value: a.value }))}
              target={
                att?.target !== undefined
                  ? { value: att.target, label: `Target ${att.target} %` }
                  : undefined
              }
            />
          </Figure>
        </div>
      </Block>
      <Block
        id="people"
        title="Who takes part"
        intro="The programme is open to people aged 18 to 29 who are out of work or underemployed. Eligibility is checked for each trainee at enrolment."
      >
        <div className="grid gap-5 lg:grid-cols-2">
          <div className="flex min-w-0 flex-col gap-5">
            <Figure
              title="Women and men"
              rows={[
                ["Women", d.female],
                ["Men", d.male],
              ]}
            >
              <Split a={{ label: "Women", value: d.female }} b={{ label: "Men", value: d.male }} />
            </Figure>
            <Figure
              title="Inclusion of priority groups"
              rows={rows(d.inclusion)}
              note="One person can belong to several groups. Shares are of all enrolled trainees."
            >
              <Bars rows={d.inclusion} total={d.trainees} />
            </Figure>
            <Figure className="flex-1" title="Age at enrolment" rows={rows(d.age)}>
              <Columns rows={d.age} />
            </Figure>
          </div>
          <div className="flex min-w-0 flex-col gap-5">
            <Figure title="Highest level of education" rows={rows(d.education)}>
              <Bars rows={d.education} />
            </Figure>
            <Figure title="Region of origin" rows={rows(d.regions)}>
              <Bars rows={d.regions} />
            </Figure>
            <Figure
              className="flex-1"
              title="Work situation before training"
              rows={rows(d.employment)}
            >
              <Bars rows={d.employment} />
            </Figure>
          </div>
        </div>
      </Block>
      <Block
        id="training"
        tone
        title="What is taught, and where"
        intro="Training is offered at three levels, in fields chosen for their relevance to the digital labour market."
      >
        <div className="grid gap-5 lg:grid-cols-2">
          <Figure
            className="lg:row-span-2"
            title="Trainees by field of training"
            rows={rows(d.fields)}
          >
            <Bars rows={d.fields} />
          </Figure>
          <Figure title="Trainees by level" rows={rows(d.levels)}>
            <Bars rows={d.levels} />
          </Figure>
          <Figure title="Trainees by training city" rows={rows(d.locations)}>
            <Bars rows={d.locations} />
          </Figure>
        </div>
        {d.feedback.total > 0 && (
          <Figure
            className="mt-5"
            title="Feedback received from trainees and the public"
            head={["Type", "Cases"]}
            rows={d.feedback.byCategory.map((x) => [
              x.label[0]!.toUpperCase() + x.label.slice(1),
              x.value,
            ])}
            note={`${fmtInt(d.feedback.resolved)} of ${fmtInt(d.feedback.total)} cases are answered and resolved.`}
          >
            <Bars
              rows={d.feedback.byCategory.map((x) => ({
                ...x,
                label: x.label[0]!.toUpperCase() + x.label.slice(1),
              }))}
            />
          </Figure>
        )}
        <div className="mt-8 flex flex-wrap items-center justify-between gap-4 border-t pt-6">
          <p className="max-w-[60ch] text-[15px] text-muted-foreground">
            All figures on this page are totals of the programme. Groups of fewer than 10 people are
            combined with another group.
          </p>
          <Button variant="outline" size="lg" onClick={() => download(d)}>
            Download the data (CSV)
          </Button>
        </div>
      </Block>
    </>
  );
}
