"use client";

import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useState } from "react";
import AuthShell, {
  buttonPrimaryClass,
  inputClass,
  labelClass,
} from "@/shared/AuthShell";
import { useResetPasswordMutation } from "@/services/auth-service";
import { getApiErrorMessage } from "@/utils/apiError";

export default function ResetPasswordPage() {
  const router = useRouter();
  const params = useSearchParams();
  const token = params?.get("token") ?? "";
  const [password, setPassword] = useState("");
  const [confirm, setConfirm] = useState("");
  const [resetPassword, { isLoading }] = useResetPasswordMutation();
  const [done, setDone] = useState(false);
  const [errorMsg, setErrorMsg] = useState("");

  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setErrorMsg("");
    if (!token) {
      setErrorMsg("Missing reset token.");
      return;
    }
    if (password !== confirm) {
      setErrorMsg("Passwords do not match.");
      return;
    }
    try {
      await resetPassword({ token, password }).unwrap();
      setDone(true);
      setTimeout(() => router.push("/admin/login"), 1500);
    } catch (err) {
      setErrorMsg(getApiErrorMessage(err, "Reset failed."));
    }
  };

  return (
    <AuthShell
      title="Set New Password"
      subtitle="Choose a strong password to secure your account"
      footer={
        <Link href="/admin/login" className="text-[#d6ac63] underline-offset-2 hover:underline">
          Back to sign in
        </Link>
      }
    >
      {done ? (
        <p className="text-sm text-black text-center font-light">
          Password updated. Redirecting to sign in…
        </p>
      ) : (
        <form onSubmit={onSubmit} noValidate className="space-y-5">
          <div>
            <label htmlFor="password" className={labelClass}>
              New password
            </label>
            <input
              id="password"
              type="password"
              required
              minLength={8}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className={inputClass}
            />
            <p className="mt-2 text-[10px] text-gray-500 tracking-wide">
              Min 8 characters, include uppercase, lowercase, and a number.
            </p>
          </div>
          <div>
            <label htmlFor="confirm" className={labelClass}>
              Confirm password
            </label>
            <input
              id="confirm"
              type="password"
              required
              minLength={8}
              value={confirm}
              onChange={(e) => setConfirm(e.target.value)}
              className={inputClass}
            />
          </div>
          {errorMsg ? <p className="text-sm text-red-500">{errorMsg}</p> : null}
          <button type="submit" disabled={isLoading} className={buttonPrimaryClass}>
            {isLoading ? "Updating…" : "Update password"}
          </button>
        </form>
      )}
    </AuthShell>
  );
}
