import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Card, PageHeader } from "@/components/pbps/page";
import { ConfirmDialog, Field, FormError, Select, TextInput } from "@/components/pbps/form";
import { ActionButton } from "@/components/pbps/action";
import { Tbl, useAct, View } from "@/components/pbps/blocks";
import { StatusBadge } from "@/components/pbps/status-badge";
import { Button } from "@/components/ui/button";
import { listRoles } from "@/api/admin";
import {
  inviteUser,
  listUsers,
  resendInvite,
  sendResetLink,
  setUserPassword,
  setUserStatus,
  updateUser,
} from "@/api/ops";
import { listProviderOptions } from "@/api/programme";
import type { AppUser } from "@/api/types";
import { useAccess } from "@/lib/access";
import { relativeTime } from "@/lib/format";

export const Route = createFileRoute("/p/$pid/admin/users")({ component: Page });
function Page() {
  const { pid } = Route.useParams();
  const { access } = useAccess();
  const q = useQuery({ queryKey: ["admin", "users"], queryFn: listUsers });
  const roles = useQuery({ queryKey: ["roles"], queryFn: listRoles });
  const [open, setOpen] = useState(false);
  const [s, setS] = useState("");
  const [off, setOff] = useState<AppUser>();
  const st = useAct(
    (v: { id: string; status: "active" | "disabled" }) => setUserStatus(v.id, v.status),
    { success: "User updated", refresh: ["admin"], onDone: () => setOff(undefined) },
  );
  const re = useAct((id: string) => resendInvite(id), { success: "Invitation sent again" });
  // A generated password or reset link is shown once, to copy and pass on.
  const [shown, setShown] = useState<{ title: string; value: string }>();
  const link = useAct((u: AppUser) => sendResetLink(u.id), {
    onDone: (r) => setShown({ title: "Password reset link (works for 24 hours)", value: r.link }),
  });
  return (
    <>
      <PageHeader
        title="Users & access"
        description="Who can sign in, and what they can do."
        actions={
          <>
            <Button variant="outline" asChild>
              <Link to="/p/$pid/admin/roles" params={{ pid }}>
                Roles & permissions
              </Link>
            </Button>
            {!open && <Button onClick={() => setOpen(true)}>Invite user</Button>}
          </>
        }
      />
      {shown && (
        <div role="status" className="mb-4 rounded-lg bg-info-soft p-3 text-[13px]">
          <p className="font-medium">{shown.title}</p>
          <p className="mt-1 break-all font-mono">{shown.value}</p>
          <div className="mt-2 flex gap-2">
            <Button
              size="sm"
              variant="outline"
              onClick={() => void navigator.clipboard.writeText(shown.value)}
            >
              Copy
            </Button>
            <Button size="sm" variant="ghost" onClick={() => setShown(undefined)}>
              Close
            </Button>
          </div>
          <p className="mt-2 text-muted-foreground">It is shown only now. Pass it on privately.</p>
        </div>
      )}
      {open && <Invite onClose={() => setOpen(false)} />}
      <TextInput
        className="mb-4 max-w-xs"
        aria-label="Search users"
        placeholder="Name, email or role"
        value={s}
        onChange={setS}
      />
      <View q={q}>
        {(d) => (
          <Card padded={false}>
            <Tbl
              head={["Name", "Email", "Role", "Provider", "Status", "Two-step", "Last login", ""]}
            >
              {d
                .filter((u) =>
                  `${u.name} ${u.email} ${u.roleLabel} ${u.providerName ?? ""}`
                    .toLowerCase()
                    .includes(s.toLowerCase()),
                )
                .map((u) => (
                  <tr key={u.id}>
                    <td className="font-medium">{u.name}</td>
                    <td>{u.email}</td>
                    <td>{u.roleLabel}</td>
                    <td>{u.providerName ?? "—"}</td>
                    <td>
                      <StatusBadge status={u.status} />
                    </td>
                    <td>{u.twoFactor ? "On" : "Off"}</td>
                    <td>{u.lastLogin ? relativeTime(u.lastLogin) : "Never"}</td>
                    <td className="whitespace-nowrap text-right">
                      {u.email !== access?.email && (
                        <ActionButton
                          variant="ghost"
                          label="Edit"
                          title={`Edit ${u.name}`}
                          fields={[
                            { key: "email", label: "Email", required: true },
                            {
                              key: "roleCode",
                              label: "Role",
                              type: "select",
                              required: true,
                              options: (roles.data ?? [])
                                .filter((x) => !!x.providerBound === !!u.providerName)
                                .map((x): [string, string] => [x.code, x.label]),
                            },
                          ]}
                          initial={{ email: u.email, roleCode: u.roleCode }}
                          run={(v) =>
                            updateUser(u.id, {
                              email: v["email"] ?? "",
                              roleCode: v["roleCode"] ?? "",
                            })
                          }
                          success="User updated"
                          refresh={["admin"]}
                        />
                      )}
                      {u.email !== access?.email && u.status === "active" && (
                        <>
                          <ActionButton
                            variant="ghost"
                            label="Set password"
                            title={`Set a password for ${u.name}`}
                            description="All their sessions end. They must choose their own password at next sign-in."
                            fields={[
                              {
                                key: "password",
                                label: "New password",
                                help: "Leave empty to generate one. At least 10 characters, letters and a number.",
                              },
                              {
                                key: "sendEmail",
                                label: "Email it to them",
                                type: "select",
                                required: true,
                                options: [
                                  ["no", "No, I will pass it on"],
                                  ["yes", "Yes, email it"],
                                ],
                              },
                            ]}
                            initial={{ password: "", sendEmail: "no" }}
                            run={(v) =>
                              setUserPassword(u.id, v["password"] ?? "", v["sendEmail"] === "yes")
                            }
                            success={(r) =>
                              r.emailed ? "Password set and emailed" : "Password set"
                            }
                            onDone={(r) =>
                              r.password &&
                              setShown({ title: `New password for ${u.name}`, value: r.password })
                            }
                          />
                          <Button
                            size="sm"
                            variant="ghost"
                            disabled={link.isPending}
                            onClick={() => link.mutate(u)}
                          >
                            Send reset link
                          </Button>
                        </>
                      )}
                      {u.email === access?.email ? (
                        "You"
                      ) : u.status === "invited" ? (
                        <Button
                          size="sm"
                          variant="ghost"
                          disabled={re.isPending}
                          onClick={() => re.mutate(u.id)}
                        >
                          Resend invitation
                        </Button>
                      ) : u.status === "active" ? (
                        <Button size="sm" variant="ghost" onClick={() => setOff(u)}>
                          Disable
                        </Button>
                      ) : (
                        <Button
                          size="sm"
                          variant="ghost"
                          disabled={st.isPending}
                          onClick={() => st.mutate({ id: u.id, status: "active" })}
                        >
                          Enable
                        </Button>
                      )}
                    </td>
                  </tr>
                ))}
            </Tbl>
          </Card>
        )}
      </View>
      <ConfirmDialog
        open={!!off}
        onOpenChange={(o) => {
          if (!o) setOff(undefined);
        }}
        title={`Disable ${off?.name ?? ""}?`}
        description="They are signed out and cannot sign in until enabled again. Their records stay."
        confirmLabel="Disable"
        destructive
        pending={st.isPending}
        onConfirm={() => off && st.mutate({ id: off.id, status: "disabled" })}
      />
    </>
  );
}
function Invite({ onClose }: { onClose: () => void }) {
  const [f, setF] = useState({ name: "", email: "", roleCode: "", providerId: "" });
  const set = (k: keyof typeof f) => (v: string) => setF((x) => ({ ...x, [k]: v }));
  const roles = useQuery({ queryKey: ["roles"], queryFn: listRoles });
  const provs = useQuery({ queryKey: ["providers", "options"], queryFn: listProviderOptions });
  const tp = roles.data?.find((r) => r.code === f.roleCode)?.providerBound ?? false;
  const m = useAct(
    (_: void) =>
      inviteUser({
        name: f.name.trim(),
        email: f.email.trim().toLowerCase(),
        roleCode: f.roleCode,
        ...(tp ? { providerId: f.providerId } : {}),
      }),
    { success: "Invitation sent", refresh: ["admin"], onError: () => {}, onDone: onClose },
  );
  const bad =
    !f.name.trim() ||
    !/^\S+@\S+\.\S+$/.test(f.email.trim()) ||
    !f.roleCode ||
    (tp && !f.providerId);
  return (
    <Card title="Invite user" className="mb-5 max-w-3xl">
      <FormError error={m.error} />
      <form
        className="grid gap-4 sm:grid-cols-2"
        onSubmit={(e) => {
          e.preventDefault();
          if (!bad) m.mutate();
        }}
      >
        <Field label="Full name" required>
          <TextInput value={f.name} onChange={set("name")} />
        </Field>
        <Field label="Email" required>
          <TextInput type="email" value={f.email} onChange={set("email")} />
        </Field>
        <Field label="Role" required>
          <Select
            value={f.roleCode}
            onChange={set("roleCode")}
            options={(roles.data ?? []).map((r) => [r.code, r.label])}
          />
        </Field>
        {tp && (
          <Field label="Provider" required>
            <Select
              value={f.providerId}
              onChange={set("providerId")}
              options={(provs.data ?? []).map((p) => [p.id, p.name])}
            />
          </Field>
        )}
        <div className="flex justify-end gap-2 sm:col-span-2">
          <Button type="button" variant="outline" onClick={onClose}>
            Cancel
          </Button>
          <Button type="submit" disabled={bad || m.isPending}>
            {m.isPending ? "Sending…" : "Send invitation"}
          </Button>
        </div>
      </form>
    </Card>
  );
}
