"use client";

import { FormEvent, useEffect, useState } from "react";

type ApiResponse<T> = {
  ok: boolean;
  data?: T;
  error?: { message: string };
};

export default function ResetPasswordPage() {
  const [token, setToken] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [isSaving, setIsSaving] = useState(false);

  useEffect(() => {
    setToken(new URLSearchParams(window.location.search).get("token") ?? "");
  }, []);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setMessage("");
    setError("");
    if (password !== confirmPassword) {
      setError("Passwords do not match.");
      return;
    }

    setIsSaving(true);
    try {
      const response = await fetch("/api/v1/auth/reset-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, password })
      });
      const result = await response.json() as ApiResponse<{ updated: boolean }>;
      if (!response.ok || !result.ok) throw new Error(result.error?.message ?? "Password could not be reset.");
      setPassword("");
      setConfirmPassword("");
      setMessage("Password updated. You can now sign in with your new password.");
    } catch (caughtError) {
      setError(caughtError instanceof Error ? caughtError.message : "Password could not be reset.");
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <main className="auth-page">
      <section className="auth-panel">
        <span className="admin-kicker">Participant Account</span>
        <h1>Reset Password</h1>
        <form className="admin-form" onSubmit={handleSubmit}>
          <label className="field">
            New Password
            <input minLength={8} onChange={(event) => setPassword(event.target.value)} required type="password" value={password} />
          </label>
          <label className="field">
            Confirm Password
            <input minLength={8} onChange={(event) => setConfirmPassword(event.target.value)} required type="password" value={confirmPassword} />
          </label>
          {error ? <p className="admin-inline-error">{error}</p> : null}
          {message ? <p className="admin-inline-note">{message}</p> : null}
          <button className="admin-primary" disabled={isSaving || !token} type="submit">{isSaving ? "Saving..." : "Save Password"}</button>
        </form>
      </section>
    </main>
  );
}
