import { createFileRoute, Link } from "@tanstack/react-router";
import { useMutation } from "@tanstack/react-query";
import { CheckCircle2 } from "lucide-react";
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 { resetPassword } from "@/api/auth";

export const Route = createFileRoute("/reset-password")({
  validateSearch: (s: Record<string, unknown>) => ({ token: String(s["token"] ?? "") }),
  head: () => ({ meta: [{ title: "Set a new password — PBPS MIS" }] }),
  component: Reset,
});

function Reset() {
  const { token } = Route.useSearch();
  const [pw, setPw] = useState("");
  const [pw2, setPw2] = useState("");
  const problems = passwordProblems(pw);
  const m = useMutation({ mutationFn: () => resetPassword(token, pw) });
  if (m.isSuccess)
    return (
      <AuthLayout title="Password updated">
        <div className="flex items-center gap-2 text-success">
          <CheckCircle2 className="h-5 w-5" /> Your password was changed.
        </div>
        <Button asChild className="mt-6 w-full">
          <Link to="/login">Sign in</Link>
        </Button>
      </AuthLayout>
    );
  return (
    <AuthLayout
      title="Set a new password"
      footer={
        <Link to="/login" className="text-primary hover:underline">
          Back to sign in
        </Link>
      }
    >
      {!token ? (
        <p>
          This link is incomplete.{" "}
          <Link to="/forgot-password" className="text-primary hover:underline">
            Request a new one
          </Link>
          .
        </p>
      ) : (
        <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">New password</span>
            <Input
              className="mt-1"
              type="password"
              autoComplete="new-password"
              value={pw}
              onChange={(e) => setPw(e.target.value)}
            />
            <PasswordChecklist pw={pw} />
          </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>
          <Button
            type="submit"
            size="lg"
            className="w-full"
            disabled={!!problems.length || pw !== pw2 || m.isPending}
          >
            {m.isPending ? "Saving…" : "Save password"}
          </Button>
        </form>
      )}
    </AuthLayout>
  );
}
