import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import {
  AuthError,
  AuthLayout,
  PasswordChecklist,
  passwordProblems,
} from "@/components/pbps/auth-layout";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { changePassword } from "@/api/auth";
import { useAccess } from "@/lib/access";
import { landAfterLogin } from "@/lib/session-nav";

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

/** Forced password change (first sign-in after an admin reset). The user cannot leave until it is done. */
function Change() {
  const navigate = useNavigate();
  const qc = useQueryClient();
  const { me } = useAccess();
  const [cur, setCur] = useState("");
  const [pw, setPw] = useState("");
  const [pw2, setPw2] = useState("");
  const problems = passwordProblems(pw, me?.user.email);
  const m = useMutation({
    mutationFn: () => changePassword(cur, pw),
    onSuccess: () => landAfterLogin(navigate, qc),
  });
  return (
    <AuthLayout
      title="Change your password"
      subtitle="Your administrator requires a new password before you continue."
    >
      <form
        className="space-y-4"
        onSubmit={(e) => {
          e.preventDefault();
          if (!problems.length && pw === pw2) m.mutate();
        }}
      >
        <AuthError message={m.error?.message} />
        <label className="block">
          <span className="font-medium">Current password</span>
          <Input
            className="mt-1"
            type="password"
            autoComplete="current-password"
            value={cur}
            onChange={(e) => setCur(e.target.value)}
          />
        </label>
        <label className="block">
          <span className="font-medium">New password</span>
          <Input
            className="mt-1"
            type="password"
            autoComplete="new-password"
            value={pw}
            onChange={(e) => setPw(e.target.value)}
          />
          <PasswordChecklist pw={pw} {...(me ? { email: me.user.email } : {})} />
        </label>
        <label className="block">
          <span className="font-medium">Confirm new 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>
        <Button
          type="submit"
          size="lg"
          className="w-full"
          disabled={!cur || !!problems.length || pw !== pw2 || m.isPending}
        >
          {m.isPending ? "Saving…" : "Save and continue"}
        </Button>
      </form>
    </AuthLayout>
  );
}
