"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

type ResetPasswordFormProps = {
  token: string;
  email: string;
};

export default function ResetPasswordForm({ token, email }: ResetPasswordFormProps) {
  const router = useRouter();
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  return (
    <form
      className="mt-6 space-y-4 rounded-benell border border-benell-stroke bg-benell-surface p-5"
      onSubmit={async (event) => {
        event.preventDefault();
        setErrorMessage(null);

        if (password.length < 8) {
          setErrorMessage("La contrasena debe tener al menos 8 caracteres.");
          return;
        }

        if (password !== confirmPassword) {
          setErrorMessage("Las contrasenas no coinciden.");
          return;
        }

        setIsSubmitting(true);

        try {
          const response = await fetch("/api/auth/reset-password", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              email,
              token,
              password,
            }),
          });

          const payload = (await response.json()) as { error?: string };
          if (!response.ok) {
            setErrorMessage(payload.error ?? "No se pudo actualizar la contrasena.");
            return;
          }

          router.replace("/login?reset=1");
        } catch {
          setErrorMessage("No se pudo actualizar la contrasena.");
        } finally {
          setIsSubmitting(false);
        }
      }}
    >
      <label className="block space-y-1.5">
        <span className="text-label font-semibold">Nueva contrasena</span>
        <input
          type="password"
          value={password}
          onChange={(event) => setPassword(event.target.value)}
          minLength={8}
          className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2 outline-none focus-visible:ring-2 focus-visible:ring-benell-brown"
          required
        />
      </label>

      <label className="block space-y-1.5">
        <span className="text-label font-semibold">Confirmar contrasena</span>
        <input
          type="password"
          value={confirmPassword}
          onChange={(event) => setConfirmPassword(event.target.value)}
          minLength={8}
          className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2 outline-none focus-visible:ring-2 focus-visible:ring-benell-brown"
          required
        />
      </label>

      {errorMessage ? <p className="text-label text-benell-red">{errorMessage}</p> : null}

      <button
        type="submit"
        disabled={isSubmitting}
        className="text-body w-full rounded-pill bg-benell-brown py-3 font-semibold text-white"
      >
        {isSubmitting ? "Guardando..." : "Actualizar contrasena"}
      </button>
    </form>
  );
}
