"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "@/components/ui/toast";

export function ChangePasswordForm({ role }: { role: string }) {
  const router = useRouter();
  const [currentPassword, setCurrentPassword] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmation, setConfirmation] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState("");

  const submit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (newPassword !== confirmation) {
      const msg = "New passwords do not match.";
      setError(msg);
      toast.error("Password mismatch", { description: msg });
      return;
    }
    setIsSubmitting(true);
    setError("");
    const response = await fetch("/api/auth/change-password", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
      body: JSON.stringify({ currentPassword, newPassword }),
    });
    const text = await response.text();
    let payload: { error?: string } = {};
    try {
      if (text && text.trim()) payload = JSON.parse(text) as { error?: string };
    } catch {
      // Non-JSON fallback
    }
    if (!response.ok) {
      const err = payload.error || "Unable to update password.";
      setError(err);
      toast.error("Update failed", { description: err });
      setIsSubmitting(false);
      return;
    }
    toast.success("Password updated!", {
      description: "Your new credentials are now active.",
    });
    router.replace(role === "admin" ? "/admin" : "/dashboard");
    router.refresh();
  };

  const inputClass =
    "mt-2 h-12 w-full rounded-2xl bg-white/72 px-4 text-sm font-medium outline-none ring-1 ring-[#b7c9d1]/45 transition focus:bg-white focus:ring-[#ef7d00]/55";

  return (
    <form onSubmit={submit} className="relative rounded-[2.5rem] bg-white/60 p-7 shadow-[0_28px_90px_rgba(24,48,59,0.1)] backdrop-blur-xl sm:p-10">
      <span className="inline-flex rounded-full bg-[#102630] px-4 py-2 text-[10px] font-extrabold uppercase tracking-[0.16em] text-white">
        Account protection
      </span>
      <h1 className="mt-6 text-4xl font-extrabold leading-[0.98] tracking-[-0.055em]">Create your private password.</h1>
      <p className="mt-4 text-sm leading-6 text-[#617078]">
        The temporary password only restores access. Replace it now before continuing to RooSports.
      </p>
      <div className="mt-8 space-y-5">
        <label className="block text-xs font-extrabold text-[#405760]">
          Temporary or current password
          <input required type="password" value={currentPassword} onChange={(event) => setCurrentPassword(event.target.value)} className={inputClass} />
        </label>
        <label className="block text-xs font-extrabold text-[#405760]">
          New password
          <input required type="password" minLength={8} value={newPassword} onChange={(event) => setNewPassword(event.target.value)} className={inputClass} />
        </label>
        <label className="block text-xs font-extrabold text-[#405760]">
          Confirm new password
          <input required type="password" minLength={8} value={confirmation} onChange={(event) => setConfirmation(event.target.value)} className={inputClass} />
        </label>
      </div>
      <p className="mt-5 text-xs leading-5 text-[#718087]">Use at least 8 characters with an uppercase letter, a number and a special symbol.</p>
      {error && <p className="mt-4 text-sm font-bold text-[#9a4338]">{error}</p>}
      <button type="submit" disabled={isSubmitting} className="mt-6 flex w-full items-center justify-between rounded-full bg-[#ef7d00] py-2 pl-6 pr-2 text-sm font-extrabold transition hover:bg-[#102630] hover:text-white disabled:opacity-50">
        {isSubmitting ? "Updating..." : "Update password"}
        <span className="grid h-11 w-11 place-items-center rounded-full bg-white text-[#102630]">
          <span className="material-symbols-outlined">arrow_forward</span>
        </span>
      </button>
    </form>
  );
}
