import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import {
  AuthError,
  AuthLayout,
  PasswordChecklist,
  passwordProblems,
} from "@/components/pbps/auth-layout";
import { DetailSkeleton } from "@/components/pbps/states";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { acceptInvite, getInvite } from "@/api/auth";
import { landAfterLogin } from "@/lib/session-nav";

export const Route = createFileRoute("/invite")({
  validateSearch: (s: Record<string, unknown>) => ({ token: String(s["token"] ?? "") }),
  head: () => ({ meta: [{ title: "Accept invitation — PBPS MIS" }] }),
  ssr: false,
  component: Invite,
});

/** Invitation links replace emailed temporary passwords (master plan §11). */
function Invite() {
  const { token } = Route.useSearch();
  const navigate = useNavigate();
  const qc = useQueryClient();
  const q = useQuery({
    queryKey: ["invite", token],
    queryFn: () => getInvite(token),
    enabled: !!token,
    retry: false,
  });
  const [name, setName] = useState("");
  const [pw, setPw] = useState("");
  const [pw2, setPw2] = useState("");
  useEffect(() => {
    if (q.data) setName(q.data.name);
  }, [q.data]);
  const m = useMutation({
    mutationFn: () => acceptInvite(token, name, pw),
    onSuccess: () => landAfterLogin(navigate, qc),
  });
  if (!token)
    return (
      <AuthLayout title="Invitation">
        <p>This invitation link is incomplete.</p>
      </AuthLayout>
    );
  if (q.isPending)
    return (
      <AuthLayout title="Invitation">
        <DetailSkeleton />
      </AuthLayout>
    );
  if (q.isError)
    return (
      <AuthLayout
        title="Invitation expired"
        footer={
          <Link to="/login" className="text-primary hover:underline">
            Go to sign in
          </Link>
        }
      >
        <AuthError message={q.error.message} />
      </AuthLayout>
    );
  const problems = passwordProblems(pw, q.data.email);
  return (
    <AuthLayout
      title="Accept your invitation"
      subtitle={
        <>
          You have been invited to PBPS MIS as <b>{q.data.roleLabel}</b>
          {q.data.providerName && (
            <>
              {" "}
              for <b>{q.data.providerName}</b>
            </>
          )}
          .
        </>
      }
    >
      <form
        className="space-y-4"
        onSubmit={(e) => {
          e.preventDefault();
          if (!problems.length && pw === pw2 && name.trim()) m.mutate();
        }}
      >
        <AuthError message={m.error?.message} />
        <label className="block">
          <span className="font-medium">Email</span>
          <Input className="mt-1" value={q.data.email} disabled />
        </label>
        <label className="block">
          <span className="font-medium">Full name</span>
          <Input className="mt-1" value={name} onChange={(e) => setName(e.target.value)} />
        </label>
        <label className="block">
          <span className="font-medium">Choose a password</span>
          <Input
            className="mt-1"
            type="password"
            autoComplete="new-password"
            value={pw}
            onChange={(e) => setPw(e.target.value)}
          />
          <PasswordChecklist pw={pw} email={q.data.email} />
        </label>
        <label className="block">
          <span className="font-medium">Confirm password</span>
          <Input
            className="mt-1"
            type="password"
            autoComplete="new-password"
            value={pw2}
            onChange={(e) => setPw2(e.target.value)}
          />
          {pw2 && pw !== pw2 && (
            <span className="text-[12px] text-danger">Passwords do not match.</span>
          )}
        </label>
        {q.data.requires2fa && (
          <p className="rounded-md bg-info-soft p-2 text-[12.5px]">
            Your role requires two-step verification. You will set it up after the first sign-in.
          </p>
        )}
        <Button
          type="submit"
          size="lg"
          className="w-full"
          disabled={!!problems.length || pw !== pw2 || !name.trim() || m.isPending}
        >
          {m.isPending ? "Activating…" : "Activate account"}
        </Button>
      </form>
    </AuthLayout>
  );
}
