import { Link } from "@tanstack/react-router";
import { ExportMenu } from "./export-menu";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Card, DateText, PageHeader } from "./page";
import { ConfirmDialog, Field, FormError, Select, TextArea, TextInput } from "./form";
import { ActionButton } from "./action";
import { Dl, Tbl, useAct, View } from "./blocks";
import { KpiCard, TargetBar } from "./kpi";
import { DetailSkeleton, EmptyState } from "./states";
import { StatusBadge } from "./status-badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  updateProviderEmails,
  activateProvider,
  amendContract,
  getProvider,
  inviteStaff,
  saveContractDetails,
  setRegistrationWindow,
  updateProvider,
  type ProviderDetail,
} from "@/api/programme";
import { useAccess, useCan } from "@/lib/access";
import { fmtDate, fmtInt, fmtPct, relativeTime } from "@/lib/format";
import { P, ROLE_LABELS, TP_ROLES } from "@/lib/roles";

const EMAIL = /^\S+@\S+\.\S+$/;
/** Used by M&E (providers/$id) and by the provider's own profile (my-provider). */
export function ProviderView({ pid, id }: { pid: string; id: string }) {
  const q = useQuery({ queryKey: ["providers", id], queryFn: () => getProvider(id) });
  return (
    <View q={q} skeleton={<DetailSkeleton />}>
      {(d) => <Body pid={pid} d={d} />}
    </View>
  );
}
function Body({ pid, d }: { pid: string; d: ProviderDetail }) {
  const { access } = useAccess();
  const { provider: p, kpis, trainings, obligations, targets, grievances, contract } = d;
  const own = !!access?.providerId;
  const manage = useCan(P.providerManage);
  const can = (k: string) => !!access?.permissions.includes(k);
  const [dlg, setDlg] = useState<"window" | "suspend" | "amend">();
  const act = useAct(
    (v: "active" | "suspended") =>
      v === "active" ? activateProvider(p.id) : updateProvider(p.id, { status: v }),
    {
      success: "Provider status updated",
      refresh: ["providers", "obligations"],
      onDone: () => setDlg(undefined),
    },
  );
  const tabs: [string, string][] = [
    // Indicators and targets are for M&E only.
    ...(own ? [] : [["overview", "Overview"] as [string, string]]),
    ["contract", "Contract"],
    ...(own ? [] : [["targets", "Targets"] as [string, string]]),
    ["staff", "Staff"],
    ["trainings", "Trainings"],
    ...(can(P.activityView) ? [["obligations", "Obligations"] as [string, string]] : []),
    ...(can(P.grievanceView) ? [["grievances", "Grievances"] as [string, string]] : []),
    ["settings", "Settings"],
  ];
  return (
    <>
      <PageHeader
        title={p.name}
        description={[p.code, p.levels.join(", "), p.locationCodes.join(" / ")]
          .filter(Boolean)
          .join(" · ")}
        actions={
          <>
            <ExportMenu
              report="provider_profile"
              formats={["pdf", "docx"]}
              label="Profile"
              params={{ providerId: p.id }}
            />
            <ExportMenu
              report="attendance_rates"
              formats={["xlsx", "csv"]}
              label="Attendance rates"
              params={{ providerId: p.id }}
              perm="attendance.view"
            />
            <StatusBadge status={p.status} size="md" />
            {manage &&
              (p.status === "active" ? (
                <Button variant="outline" onClick={() => setDlg("suspend")}>
                  Suspend
                </Button>
              ) : (
                <Button disabled={act.isPending} onClick={() => act.mutate("active")}>
                  Activate
                </Button>
              ))}
            {manage && p.projectRegistrationOpen !== false && (
              <Button variant="outline" onClick={() => setDlg("window")}>
                Registration window
              </Button>
            )}
          </>
        }
      />
      <div className="mb-5 rounded-xl border bg-card p-4 text-[13px]">
        <div className="flex flex-wrap justify-between gap-2">
          <span>
            Registered <b>{fmtInt(p.registered)}</b> of {fmtInt(p.maxRegistration)} allowed (target{" "}
            {fmtInt(p.contractTarget)})
          </span>
          <span>
            Registration{" "}
            {p.registrationWindow?.from && (
              <>
                from <DateText value={p.registrationWindow.from} />{" "}
              </>
            )}
            {p.registrationOpen
              ? "open"
              : p.projectRegistrationOpen === false
                ? "closed for the whole project"
                : "closed"}
            {p.registrationWindow?.lateUntil && (
              <>
                , reopened until <DateText value={p.registrationWindow.lateUntil} />
              </>
            )}
          </span>
        </div>
        <div className="mt-2">
          <TargetBar value={p.registered} target={p.contractTarget} max={p.maxRegistration || 1} />
        </div>
      </div>
      <Tabs defaultValue={own ? "contract" : "overview"}>
        <TabsList className="mb-4 h-auto flex-wrap">
          {tabs.map(([k, l]) => (
            <TabsTrigger key={k} value={k}>
              {l}
            </TabsTrigger>
          ))}
        </TabsList>
        <TabsContent value="overview">
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
            {kpis.map((k) => (
              <KpiCard key={k.indicatorCode} k={k} />
            ))}
          </div>
        </TabsContent>
        <TabsContent value="contract" className="space-y-4">
          <Card
            title="Current contract"
            actions={
              can(P.contractManage) &&
              !own && (
                <span className="flex gap-2">
                  <ActionButton
                    label="Edit details"
                    title="Contract details"
                    description="Deadlines counted from the signing date appear once it is filled in."
                    fields={[
                      { key: "number", label: "Contract number" },
                      { key: "signedDate", label: "Signed on", type: "date" },
                      { key: "start", label: "Start", type: "date" },
                      { key: "end", label: "End", type: "date" },
                    ]}
                    initial={{
                      number: contract.number,
                      signedDate: contract.signedDate,
                      start: contract.start,
                      end: contract.end,
                    }}
                    run={(v) =>
                      saveContractDetails(
                        p.id,
                        Object.fromEntries(Object.entries(v).filter(([, x]) => x.trim())),
                      )
                    }
                    success="Contract saved"
                    refresh={["providers", "obligations"]}
                  />
                  <Button size="sm" variant="outline" onClick={() => setDlg("amend")}>
                    Amend
                  </Button>
                </span>
              )
            }
          >
            <Dl
              items={[
                ["Number", contract.number],
                ["Status", <StatusBadge key="s" status={contract.status} />],
                ["Signed", <DateText key="d" value={contract.signedDate} />],
                [
                  "Period",
                  <span key="p">
                    <DateText value={contract.start} /> to <DateText value={contract.end} />
                  </span>,
                ],
                ["Target", `${fmtInt(contract.target)} trainees`],
              ]}
            />
          </Card>
          <Card title="Versions" padded={false}>
            <Tbl head={[">Version", ">Target", "In effect from", "Reason"]}>
              {contract.versions.map((v) => (
                <tr key={v.version}>
                  <td className="text-right">{v.version}</td>
                  <td className="text-right">{fmtInt(v.target)}</td>
                  <td>
                    <DateText value={v.effectiveFrom} />
                  </td>
                  <td>{v.note}</td>
                </tr>
              ))}
            </Tbl>
          </Card>
        </TabsContent>
        <TabsContent value="targets">
          <Card
            padded={false}
            {...(can(P.targetManage)
              ? {
                  title: "Targets",
                  actions: (
                    <Link
                      className="text-[13px] text-primary hover:underline"
                      to="/p/$pid/targets"
                      params={{ pid }}
                    >
                      Edit targets
                    </Link>
                  ),
                }
              : {})}
          >
            <Tbl head={["#", "Indicator", ">Project default", ">Provider target"]}>
              {targets.map((t) => (
                <tr key={t.indicator.code}>
                  <td>{t.indicator.no}</td>
                  <td>{t.indicator.name}</td>
                  <td className="text-right text-muted-foreground">{t.default}</td>
                  <td className="text-right">
                    {t.target !== undefined ? (
                      <b>{t.target}</b>
                    ) : (
                      <span className="text-muted-foreground">Uses default</span>
                    )}
                  </td>
                </tr>
              ))}
            </Tbl>
          </Card>
        </TabsContent>
        <TabsContent value="staff">
          <Staff d={d} can={can(P.staffManage)} />
        </TabsContent>
        <TabsContent value="trainings">
          <Card padded={false}>
            {trainings.length === 0 ? (
              <EmptyState title="No trainings yet" text="Trainings appear once they are added." />
            ) : (
              <Tbl head={["Training", "Level", "Sites", ">Classes", ">Trainees", ">Attendance"]}>
                {trainings.map((t) => (
                  <tr key={t.id}>
                    <td>
                      <Link
                        className="font-medium hover:text-primary"
                        to="/p/$pid/trainings/$id"
                        params={{ pid, id: t.id }}
                      >
                        {t.title}
                      </Link>
                    </td>
                    <td className="capitalize">{t.level}</td>
                    <td>{t.locationCodes.join(", ")}</td>
                    <td className="text-right">{t.classesCount}</td>
                    <td className="text-right">{fmtInt(t.traineesCount)}</td>
                    <td className="text-right">{fmtPct(t.attendanceRate)}</td>
                  </tr>
                ))}
              </Tbl>
            )}
          </Card>
        </TabsContent>
        <TabsContent value="obligations">
          <Card padded={false}>
            <Tbl head={["Activity", "Scope", "Due", "Status"]}>
              {obligations.map((o) => (
                <tr key={o.id}>
                  <td>
                    <Link
                      className="font-medium hover:text-primary"
                      to="/p/$pid/obligations/$id"
                      params={{ pid, id: o.id }}
                    >
                      {o.activity.name}
                    </Link>
                  </td>
                  <td>{o.scopeLabel}</td>
                  <td>
                    <DateText value={o.dueDate} />
                  </td>
                  <td>
                    <StatusBadge status={o.status} />
                  </td>
                </tr>
              ))}
            </Tbl>
          </Card>
        </TabsContent>
        <TabsContent value="grievances">
          <Card padded={false}>
            {grievances.length === 0 ? (
              <EmptyState title="No cases" text="Cases about this provider appear here." />
            ) : (
              <Tbl head={["Reference", "Subject", "Due", "Status"]}>
                {grievances.map((g) => (
                  <tr key={g.id}>
                    <td>
                      <Link
                        className="font-mono text-primary hover:underline"
                        to="/p/$pid/grievances/$id"
                        params={{ pid, id: g.id }}
                      >
                        {g.ref}
                      </Link>
                    </td>
                    <td>{g.subject}</td>
                    <td>
                      <DateText value={g.dueAt} />
                    </td>
                    <td>
                      <StatusBadge status={g.status} />
                    </td>
                  </tr>
                ))}
              </Tbl>
            )}
          </Card>
        </TabsContent>
        <TabsContent value="settings">
          <Settings key={p.id} d={d} can={manage || (own && can(P.staffManage))} />
        </TabsContent>
      </Tabs>
      <ConfirmDialog
        open={dlg === "suspend"}
        onOpenChange={(o) => setDlg(o ? "suspend" : undefined)}
        title={`Suspend ${p.name}?`}
        description="Its staff can no longer submit data. Nothing is deleted, and you can activate it again."
        confirmLabel="Suspend"
        destructive
        pending={act.isPending}
        onConfirm={() => act.mutate("suspended")}
      />
      {dlg === "window" && <WindowDialog d={d} onClose={() => setDlg(undefined)} />}
      {dlg === "amend" && <Amend d={d} onClose={() => setDlg(undefined)} />}
    </>
  );
}
function Staff({ d, can }: { d: ProviderDetail; can: boolean }) {
  const [open, setOpen] = useState(false);
  const [f, setF] = useState({ name: "", email: "", roleCode: "" });
  const bad = !f.name.trim() || !EMAIL.test(f.email.trim()) || !f.roleCode;
  const m = useAct(
    (_: void) =>
      inviteStaff(d.provider.id, {
        name: f.name.trim(),
        email: f.email.trim().toLowerCase(),
        roleCode: f.roleCode,
        scopes: [],
      }),
    {
      success: "Invitation sent",
      refresh: ["providers", "admin"],
      onError: () => {},
      onDone: () => {
        setOpen(false);
        setF({ name: "", email: "", roleCode: "" });
      },
    },
  );
  return (
    <Card
      title="Staff"
      padded={false}
      actions={
        can &&
        !open && (
          <Button size="sm" onClick={() => setOpen(true)}>
            Invite staff
          </Button>
        )
      }
    >
      {open && (
        <div className="border-b p-4">
          <FormError error={m.error} />
          <div className="grid gap-3 sm:grid-cols-3">
            <Field label="Full name" required>
              <TextInput value={f.name} onChange={(v) => setF((s) => ({ ...s, name: v }))} />
            </Field>
            <Field label="Email" required>
              <TextInput
                type="email"
                value={f.email}
                onChange={(v) => setF((s) => ({ ...s, email: v }))}
              />
            </Field>
            <Field label="Role" required>
              <Select
                value={f.roleCode}
                onChange={(v) => setF((s) => ({ ...s, roleCode: v }))}
                options={TP_ROLES.map((r): [string, string] => [r, ROLE_LABELS[r]])}
              />
            </Field>
          </div>
          <div className="mt-3 flex justify-end gap-2">
            <Button variant="outline" onClick={() => setOpen(false)}>
              Cancel
            </Button>
            <Button disabled={bad || m.isPending} onClick={() => m.mutate()}>
              {m.isPending ? "Sending…" : "Send invitation"}
            </Button>
          </div>
        </div>
      )}
      {d.staff.length === 0 ? (
        <EmptyState title="No staff yet" text="Invite the organisation's admin first." />
      ) : (
        <Tbl head={["Name", "Email", "Role", "Scope", "Status", "Last login"]}>
          {d.staff.map((s) => (
            <tr key={s.id}>
              <td className="font-medium">{s.name}</td>
              <td>{s.email}</td>
              <td>{s.roleLabel}</td>
              <td>{s.scopes.join(", ") || "Whole organisation"}</td>
              <td>
                <StatusBadge status={s.status} />
              </td>
              <td>{s.lastLogin ? relativeTime(s.lastLogin) : "Never"}</td>
            </tr>
          ))}
        </Tbl>
      )}
    </Card>
  );
}
function Settings({ d, can }: { d: ProviderDetail; can: boolean }) {
  const p = d.provider;
  const [f, setF] = useState({
    notificationEmail: p.notificationEmail ?? "",
    replyToEmail: p.replyToEmail ?? "",
  });
  const bad = (v: string) => (EMAIL.test(v.trim()) ? undefined : "Enter a valid email address.");
  const m = useAct((_: void) => updateProviderEmails(p.id, f), {
    success: "Settings saved",
    refresh: ["providers"],
  });
  return (
    <Card className="max-w-2xl">
      <div className="grid gap-4 sm:grid-cols-2">
        <Field
          label="Notification email"
          help="System emails go here."
          error={can ? bad(f.notificationEmail) : undefined}
        >
          <TextInput
            type="email"
            disabled={!can}
            value={f.notificationEmail}
            onChange={(v) => setF((s) => ({ ...s, notificationEmail: v }))}
          />
        </Field>
        <Field
          label="Reply-to email"
          help="Shown to people who submit feedback."
          error={can ? bad(f.replyToEmail) : undefined}
        >
          <TextInput
            type="email"
            disabled={!can}
            value={f.replyToEmail}
            onChange={(v) => setF((s) => ({ ...s, replyToEmail: v }))}
          />
        </Field>
      </div>
      {can && (
        <div className="mt-4 flex justify-end">
          <Button
            disabled={m.isPending || !!bad(f.notificationEmail) || !!bad(f.replyToEmail)}
            onClick={() => m.mutate()}
          >
            Save settings
          </Button>
        </div>
      )}
    </Card>
  );
}
function WindowDialog({ d, onClose }: { d: ProviderDetail; onClose: () => void }) {
  const w = d.provider.registrationWindow;
  const today = new Date().toISOString().slice(0, 10);
  const closed = !!w?.until && w.until < today;
  const [from, setFrom] = useState(w?.from ?? "");
  const [until, setUntil] = useState(closed ? "" : (w?.until ?? ""));
  const [reason, setReason] = useState("");
  const m = useAct(
    (_: void) =>
      setRegistrationWindow(d.provider.id, closed ? { late: { until, reason } } : { from, until }),
    { success: "Registration window saved", refresh: ["providers"], onDone: onClose },
  );
  return (
    <ConfirmDialog
      open
      onOpenChange={(o) => {
        if (!o) onClose();
      }}
      title={closed ? "Grant a late registration window" : "Registration window"}
      {...(closed ? { description: `Registration closed on ${fmtDate(w!.until)}.` } : {})}
      confirmLabel="Save"
      pending={
        m.isPending || !until || (closed ? until < today || !reason.trim() : !from || until < from)
      }
      onConfirm={() => m.mutate()}
    >
      <div className="space-y-3">
        {!closed && (
          <Field label="Open from" required>
            <Input type="date" value={from} onChange={(e) => setFrom(e.target.value)} />
          </Field>
        )}
        <Field
          label="Open until"
          required
          error={
            !closed && from && until && until < from ? "Must be after the opening date." : undefined
          }
        >
          <Input type="date" value={until} onChange={(e) => setUntil(e.target.value)} />
        </Field>
        {closed && (
          <Field label="Reason" required>
            <TextArea rows={2} value={reason} onChange={setReason} />
          </Field>
        )}
      </div>
    </ConfirmDialog>
  );
}
function Amend({ d, onClose }: { d: ProviderDetail; onClose: () => void }) {
  const [t, setT] = useState(String(d.provider.contractTarget));
  const [from, setFrom] = useState("");
  const [note, setNote] = useState("");
  const n = Number(t);
  const ok = Number.isInteger(n) && n > 0;
  const m = useAct(
    (_: void) => amendContract(d.provider.id, { target: n, effectiveFrom: from, note }),
    { success: "Contract amended", refresh: ["providers", "dashboard", "kpi"], onDone: onClose },
  );
  return (
    <ConfirmDialog
      open
      onOpenChange={(o) => {
        if (!o) onClose();
      }}
      title="Amend contract"
      description="Creates a new version. Earlier versions are kept."
      confirmLabel="Save amendment"
      pending={m.isPending || !ok || !from || !note.trim()}
      onConfirm={() => m.mutate()}
    >
      <div className="space-y-3">
        <Field
          label="Target trainees"
          required
          error={ok ? undefined : "Enter a whole number above 0."}
        >
          <TextInput inputMode="numeric" value={t} onChange={setT} />
        </Field>
        <Field label="In effect from" required>
          <Input type="date" value={from} onChange={(e) => setFrom(e.target.value)} />
        </Field>
        <Field label="Reason" required>
          <TextArea rows={2} value={note} onChange={setNote} />
        </Field>
      </div>
    </ConfirmDialog>
  );
}
