import { createFileRoute } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Card, DateText, PageHeader } from "@/components/pbps/page";
import { Field, FormError, Select, TextInput, YesNo } from "@/components/pbps/form";
import { ActionButton, type ActionField } from "@/components/pbps/action";
import { SubNav, Tbl, useAct, View } from "@/components/pbps/blocks";
import { StatusBadge } from "@/components/pbps/status-badge";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  createDefinition,
  listActivityDefinitions,
  previewSchedules,
  saveSchedule,
  updateDefinition,
} from "@/api/activities";
import { listProviderOptions } from "@/api/programme";
import type { ActivitySchedule } from "@/api/types-extra";
import { shortIndicator } from "@/lib/indicators";
import { ACTIVITY_NAV } from "@/lib/sections";

export const Route = createFileRoute("/p/$pid/activities/setup")({ component: Page });
const NAME_FIELDS: ActionField[] = [
  { key: "name", label: "Name", required: true },
  { key: "description", label: "Description", type: "area" },
];
const ANCHOR: [ActivitySchedule["anchor"], string][] = [
  ["contract_signed_date", "Contract signed"],
  ["provider_first_class_start", "Provider's first class start"],
  ["training_planned_start", "Training planned start"],
  ["site_first_class_start", "Site's first class start"],
  ["class_start", "Class start"],
  ["class_end", "Class end"],
];
const day = (n: number) => (n === 0 ? "same day" : n < 0 ? `${-n} days before` : `${n} days after`);
function Page() {
  const { pid } = Route.useParams();
  const [edit, setEdit] = useState<{ def: string; name: string; s: ActivitySchedule }>();
  const [prov, setProv] = useState("");
  const q = useQuery({ queryKey: ["activity-definitions"], queryFn: listActivityDefinitions });
  const provs = useQuery({ queryKey: ["providers", "options"], queryFn: listProviderOptions });
  const pv = useQuery({
    queryKey: ["activity-definitions", "preview", prov],
    queryFn: () => previewSchedules(prov),
    enabled: !!prov,
  });
  return (
    <>
      <PageHeader
        title="Activity definitions & schedules"
        description="When each piece of evidence opens, is due and closes."
        actions={
          <ActionButton
            size="default"
            variant="default"
            label="New activity"
            title="New activity"
            description="After saving, set its schedule below."
            fields={[
              { key: "code", label: "Code (small letters and _)", required: true },
              ...NAME_FIELDS,
              {
                key: "scope",
                label: "Submitted",
                type: "select",
                required: true,
                options: [
                  ["provider", "Once per provider"],
                  ["training", "Once per training"],
                ],
              },
            ]}
            initial={{ scope: "provider" }}
            run={(v) =>
              createDefinition({
                code: v["code"],
                name: v["name"],
                description: v["description"] ?? "",
                scope: v["scope"],
                evidence: {
                  types: [],
                  minFiles: 1,
                  checklist: [],
                },
              })
            }
            success="Activity created"
            refresh={["activity-definitions", "obligations"]}
          />
        }
      />
      <SubNav pid={pid} items={ACTIVITY_NAV} />
      <View q={q}>
        {(d) => (
          <div className="space-y-4">
            {d.map((a) => (
              <Card
                key={a.id}
                padded={false}
                title={
                  <>
                    {a.name}{" "}
                    <span className="font-normal text-muted-foreground">
                      per {a.scope}
                      {a.linkedIndicator && `, counts for ${shortIndicator(a.linkedIndicator)}`}
                    </span>
                  </>
                }
                actions={
                  <span className="flex items-center gap-2">
                    <StatusBadge status={a.active ? "active" : "disabled"} />
                    <ActionButton
                      variant="ghost"
                      label="Edit"
                      title={`Edit ${a.name}`}
                      fields={[
                        ...NAME_FIELDS,
                        {
                          key: "active",
                          label: "In use",
                          type: "select",
                          required: true,
                          options: [
                            ["yes", "Yes"],
                            ["no", "No"],
                          ],
                        },
                      ]}
                      initial={{
                        name: a.name,
                        description: a.description ?? "",
                        active: a.active ? "yes" : "no",
                      }}
                      run={(v) =>
                        updateDefinition(a.id, {
                          name: v["name"],
                          description: v["description"] ?? "",
                          active: v["active"] === "yes",
                        })
                      }
                      success="Activity saved"
                      refresh={["activity-definitions", "obligations"]}
                    />
                  </span>
                }
              >
                <Tbl
                  head={[
                    "Applies to",
                    "Counted from",
                    "Opens",
                    "Due",
                    ">Grace days",
                    "Repeats",
                    "Breakdowns extend",
                    "",
                    "",
                  ]}
                >
                  {a.schedules.map((s) => (
                    <tr key={s.id} className={s.active ? "" : "text-muted-foreground"}>
                      <td>{s.appliesTo}</td>
                      <td>{ANCHOR.find(([k]) => k === s.anchor)?.[1]}</td>
                      <td>{day(s.openOffset)}</td>
                      <td>{day(s.dueOffset)}</td>
                      <td className="text-right">{s.graceDays}</td>
                      <td>
                        {s.repeatEvery
                          ? `Every ${s.repeatEvery} days, ${s.repeatCount} times`
                          : "Once"}
                      </td>
                      <td>{s.breakdownExtends ? "Yes" : "No"}</td>
                      <td>
                        <StatusBadge
                          status={s.active ? "active" : "disabled"}
                          label={s.legacy ? "V1 rule" : s.active ? "Active" : "Off"}
                        />
                      </td>
                      <td className="text-right">
                        {!s.legacy && (
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={() => setEdit({ def: a.id, name: a.name, s })}
                          >
                            Edit
                          </Button>
                        )}
                      </td>
                    </tr>
                  ))}
                </Tbl>
              </Card>
            ))}
          </div>
        )}
      </View>
      <Card title="Preview for a provider" className="mt-6">
        <div className="mb-3 w-72">
          <Select
            ariaLabel="Provider"
            value={prov}
            onChange={setProv}
            placeholder="Choose a provider"
            options={(provs.data ?? []).map((p) => [p.id, p.name])}
          />
        </div>
        {prov && (
          <View
            q={pv}
            empty={{ title: "Nothing to generate", text: "This provider has no classes yet." }}
          >
            {(d) => (
              <Tbl head={["Activity", "Scope", "Opens", "Due", "Closes", "Change"]}>
                {d.map((o) => (
                  <tr key={o.id}>
                    <td>{o.activity.name}</td>
                    <td>{o.scopeLabel}</td>
                    <td>
                      <DateText value={o.openDate} />
                    </td>
                    <td>
                      <DateText value={o.dueDate} />
                    </td>
                    <td>
                      <DateText value={o.closeDate} />
                    </td>
                    <td className="capitalize">{o.change}</td>
                  </tr>
                ))}
              </Tbl>
            )}
          </View>
        )}
      </Card>
      {edit && <Edit key={edit.s.id} {...edit} onClose={() => setEdit(undefined)} />}
    </>
  );
}
function Edit({
  def,
  name,
  s,
  onClose,
}: {
  def: string;
  name: string;
  s: ActivitySchedule;
  onClose: () => void;
}) {
  const [f, setF] = useState({
    anchor: s.anchor,
    openOffset: String(s.openOffset),
    dueOffset: String(s.dueOffset),
    graceDays: String(s.graceDays),
    breakdownExtends: s.breakdownExtends,
    active: s.active,
  });
  const int = (v: string) => /^-?\d+$/.test(v);
  const m = useAct(
    (_: void) =>
      saveSchedule(def, {
        ...s,
        ...f,
        openOffset: Number(f.openOffset),
        dueOffset: Number(f.dueOffset),
        graceDays: Number(f.graceDays),
      }),
    {
      success: "Schedule saved",
      refresh: ["activity-definitions", "obligations"],
      onError: () => {},
      onDone: onClose,
    },
  );
  const bad = !int(f.openOffset) || !int(f.dueOffset) || !/^\d+$/.test(f.graceDays);
  const order = !bad && Number(f.dueOffset) < Number(f.openOffset);
  const num = (k: "openOffset" | "dueOffset" | "graceDays", l: string, help?: string) => (
    <Field
      label={l}
      required
      help={help}
      error={k === "dueOffset" && order ? "Due cannot be before opening." : undefined}
    >
      <TextInput
        inputMode="numeric"
        value={f[k]}
        onChange={(v) => setF((x) => ({ ...x, [k]: v }))}
      />
    </Field>
  );
  return (
    <Dialog
      open
      onOpenChange={(o) => {
        if (!o) onClose();
      }}
    >
      <DialogContent>
        <DialogHeader>
          <DialogTitle>
            {name}: {s.appliesTo}
          </DialogTitle>
        </DialogHeader>
        <FormError error={m.error} />
        <div className="space-y-3">
          <Field label="Counted from">
            <Select
              value={f.anchor}
              onChange={(v) =>
                v && setF((x) => ({ ...x, anchor: v as ActivitySchedule["anchor"] }))
              }
              options={ANCHOR}
            />
          </Field>
          <div className="grid grid-cols-3 gap-3">
            {num("openOffset", "Opens (days)", "Negative is before")}
            {num("dueOffset", "Due (days)")}
            {num("graceDays", "Grace days")}
          </div>
          <Field label="Approved breakdowns extend the dates">
            <YesNo
              name="bd"
              value={f.breakdownExtends}
              onChange={(v) => setF((x) => ({ ...x, breakdownExtends: v }))}
            />
          </Field>
          <Field label="Active">
            <YesNo
              name="ac"
              value={f.active}
              onChange={(v) => setF((x) => ({ ...x, active: v }))}
            />
          </Field>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={onClose}>
            Cancel
          </Button>
          <Button disabled={bad || order || m.isPending} onClick={() => m.mutate()}>
            Save schedule
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
