import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { Redirect } from "@/components/pbps/redirect";
import { useQuery } from "@tanstack/react-query";
import { ArrowRight, FolderKanban, LogOut, MapPin, Plus, Users } from "lucide-react";
import { useState } from "react";
import { Wordmark } from "@/components/pbps/brand";
import { useAct } from "@/components/pbps/blocks";
import { Field, FormError, Select, TextArea, TextInput } from "@/components/pbps/form";
import { EmptyState, ErrorState, KpiGridSkeleton } from "@/components/pbps/states";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { createProject, listProjects } from "@/api/admin";
import { fieldErrorMap } from "@/api/client";
import { getAccess } from "@/api/auth";
import { setProjectId } from "@/api/http";
import type { ProjectSummary } from "@/api/types-extra";
import { fmtDate } from "@/lib/dates";
import { fmtInt } from "@/lib/format";
import { useAccess } from "@/lib/access";
import { homePathFor } from "@/lib/roles";

export const Route = createFileRoute("/projects")({
  ssr: false,
  head: () => ({ meta: [{ title: "Projects — PBPS MIS" }] }),
  component: Projects,
});

function Projects() {
  const { me, ready, signOut } = useAccess();
  const navigate = useNavigate();
  const [s, setS] = useState("");
  const [create, setCreate] = useState(false);
  const q = useQuery({ queryKey: ["projects"], queryFn: listProjects, enabled: !!me });
  if (ready && !me) return <Redirect to="/login" />;
  const admin = !!q.data?.some((p) => p.roleCode === "system_admin");
  const open = async (id: string) => {
    setProjectId(id);
    const a = await getAccess();
    void navigate({
      to: `/p/$pid/${homePathFor(a.roleCode)}` as "/p/$pid/home",
      params: { pid: id },
    });
  };
  const shown = (q.data ?? []).filter((p) =>
    `${p.code} ${p.title} ${p.donor ?? ""} ${p.location ?? ""}`
      .toLowerCase()
      .includes(s.toLowerCase()),
  );
  return (
    <div className="min-h-screen bg-background">
      <header className="border-b bg-card">
        <div className="mx-auto flex h-14 max-w-5xl items-center justify-between px-4">
          <Wordmark />
          <Button
            variant="ghost"
            onClick={() => void signOut().then(() => navigate({ to: "/login" }))}
          >
            <LogOut /> Sign out
          </Button>
        </div>
      </header>
      <main className="mx-auto max-w-5xl px-4 py-10">
        <div className="flex flex-wrap items-end justify-between gap-4">
          <div>
            <h1 className="font-display text-2xl font-bold">Choose a project</h1>
            <p className="mt-1 text-muted-foreground">
              Each project has its own providers, trainees, users and results.
            </p>
          </div>
          {admin && (
            <Button onClick={() => setCreate(true)}>
              <Plus /> New project
            </Button>
          )}
        </div>
        {(q.data?.length ?? 0) > 4 && (
          <TextInput
            className="mt-6 max-w-xs"
            aria-label="Search projects"
            placeholder="Code, title, donor or place"
            value={s}
            onChange={setS}
          />
        )}
        <div className="mt-6">
          {q.isPending ? (
            <KpiGridSkeleton n={2} />
          ) : q.isError ? (
            <ErrorState error={q.error} onRetry={() => void q.refetch()} />
          ) : !shown.length ? (
            <EmptyState
              icon={FolderKanban}
              title={s ? "No project matches" : "No projects"}
              text={
                s
                  ? "Try another word."
                  : "You are not a member of any project yet. Ask your administrator to add you."
              }
            />
          ) : (
            <ul className="grid gap-4 sm:grid-cols-2">
              {shown.map((p) => (
                <li key={p.id}>
                  <button
                    type="button"
                    onClick={() => void open(p.id)}
                    className="group flex h-full w-full flex-col rounded-xl border bg-card p-5 text-left shadow-(--shadow-card) hover:border-primary"
                  >
                    <span className="flex w-full items-start justify-between gap-3">
                      <span>
                        <span className="block font-mono text-[12px] text-muted-foreground">
                          {p.code}
                        </span>
                        <span className="mt-0.5 block font-display text-lg font-semibold">
                          {p.title}
                        </span>
                      </span>
                      <ArrowRight className="mt-1 h-4 w-4 text-subtle group-hover:text-primary" />
                    </span>
                    <span className="mt-1 text-[13px] text-muted-foreground">
                      {p.roleLabel}
                      {p.providerName ? ` · ${p.providerName}` : ""}
                    </span>
                    <span className="mt-4 flex flex-wrap gap-x-4 gap-y-1 text-[13px] tabular">
                      <span className="flex items-center gap-1.5">
                        <Users className="h-3.5 w-3.5" aria-hidden />
                        {fmtInt(p.trainees)} trainees
                      </span>
                      <span>{p.providers} providers</span>
                      {p.location && (
                        <span className="flex items-center gap-1.5">
                          <MapPin className="h-3.5 w-3.5" aria-hidden />
                          {p.location}
                        </span>
                      )}
                    </span>
                    {(p.donor || p.start) && (
                      <span className="mt-2 text-[12.5px] text-muted-foreground">
                        {[p.donor, p.start && `${fmtDate(p.start)} to ${fmtDate(p.end ?? "")}`]
                          .filter(Boolean)
                          .join(" · ")}
                      </span>
                    )}
                  </button>
                </li>
              ))}
            </ul>
          )}
        </div>
      </main>
      {create && q.data && (
        <Create projects={q.data} onClose={() => setCreate(false)} onDone={(id) => void open(id)} />
      )}
    </div>
  );
}
const EMPTY = {
  code: "",
  title: "",
  donor: "",
  sector: "",
  location: "",
  start: "",
  end: "",
  description: "",
};
function Create({
  projects,
  onClose,
  onDone,
}: {
  projects: ProjectSummary[];
  onClose: () => void;
  onDone: (id: string) => void;
}) {
  const mine = projects.filter((p) => p.roleCode === "system_admin");
  const [f, setF] = useState({ ...EMPTY, copyFrom: mine[0]?.id ?? "" });
  const [show, setShow] = useState(false);
  const set = (k: keyof typeof f) => (v: string) => setF((s) => ({ ...s, [k]: v }));
  const m = useAct(
    (_: void) => createProject(Object.fromEntries(Object.entries(f).filter(([, v]) => v.trim()))),
    {
      success: (x) => `Project ${x.code} created`,
      refresh: ["projects", "auth"],
      onError: () => {},
      onDone: (x) => onDone(x.id),
    },
  );
  const server = fieldErrorMap(m.error);
  const err: Record<string, string | undefined> = {
    code: /^[A-Z0-9_-]{2,20}$/.test(f.code) ? undefined : "2 to 20 capital letters, numbers or -.",
    title: f.title.trim().length >= 3 ? undefined : "Write the full name.",
    start: f.start ? undefined : "Choose a date.",
    end: !f.end ? "Choose a date." : f.end <= f.start ? "It must be after the start." : undefined,
  };
  const e = (k: string) => server[k] ?? (show ? err[k] : undefined);
  return (
    <Dialog
      open
      onOpenChange={(o) => {
        if (!o) onClose();
      }}
    >
      <DialogContent className="max-h-[90vh] max-w-2xl overflow-y-auto">
        <DialogHeader>
          <DialogTitle>New project</DialogTitle>
        </DialogHeader>
        <FormError error={m.error} />
        <form
          noValidate
          className="grid gap-4 sm:grid-cols-2"
          onSubmit={(x) => {
            x.preventDefault();
            setShow(true);
            if (!Object.values(err).some(Boolean)) m.mutate();
          }}
        >
          <Field label="Code" required error={e("code")} help="Part of every trainee ID.">
            <TextInput
              value={f.code}
              maxLength={20}
              onChange={(v) => set("code")(v.toUpperCase().replace(/\s/g, ""))}
            />
          </Field>
          <Field label="Title" required error={e("title")}>
            <TextInput value={f.title} onChange={set("title")} maxLength={190} />
          </Field>
          <Field label="Donor">
            <TextInput value={f.donor} onChange={set("donor")} />
          </Field>
          <Field label="Sector">
            <TextInput value={f.sector} onChange={set("sector")} />
          </Field>
          <Field label="Start" required error={e("start")}>
            <Input type="date" value={f.start} onChange={(x) => set("start")(x.target.value)} />
          </Field>
          <Field label="End" required error={e("end")}>
            <Input type="date" value={f.end} onChange={(x) => set("end")(x.target.value)} />
          </Field>
          <Field label="Place">
            <TextInput value={f.location} onChange={set("location")} />
          </Field>
          <Field
            label="Copy the set-up of"
            help="Policies, indicators, activities, holidays and reminders. Never people or results."
          >
            <Select
              value={f.copyFrom}
              onChange={set("copyFrom")}
              placeholder="Start empty"
              options={mine.map((p): [string, string] => [p.id, `${p.code} · ${p.title}`])}
            />
          </Field>
          <Field label="Description" className="sm:col-span-2">
            <TextArea rows={2} value={f.description} onChange={set("description")} />
          </Field>
          <DialogFooter className="sm:col-span-2">
            <Button type="button" variant="outline" onClick={onClose}>
              Cancel
            </Button>
            <Button type="submit" disabled={m.isPending}>
              {m.isPending ? "Creating…" : "Create project"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
