"use client";

import { useState, useRef } from "react";
import Link from "next/link";
import TurnstileWidget, { TurnstileWidgetHandle } from "@/components/shared/turnstile-widget";

export default function ForgotPasswordPage() {
  const turnstileRef = useRef<TurnstileWidgetHandle>(null);
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);
  const [loading, setLoading] = useState(false);
  const [captchaToken, setCaptchaToken] = useState("");

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setSuccess(false);

    if (!captchaToken) {
      setError("Please complete the CAPTCHA challenge.");
      return;
    }

    setLoading(true);

    try {
      const res = await fetch("/api/forgot-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, captcha_token: captchaToken }),
      });

      const result = await res.json();

      if (!res.ok) {
        // The token was already spent verifying this request server-side,
        // even though it failed for an unrelated reason. Reset so the retry
        // gets a fresh one instead of reusing a dead token.
        turnstileRef.current?.reset();
        setCaptchaToken("");
        setError(result.message || "Failed to send reset email");
        return;
      }

      setSuccess(true);
    } catch {
      setError("An unexpected error occurred");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="bg-surface rounded-lg p-8 shadow-lg">
      <h1 className="text-2xl font-bold text-text mb-2 text-center">
        Forgot Password
      </h1>
      <p className="text-text-muted text-center mb-6 text-sm">
        Enter your email and we&apos;ll send you a reset link
      </p>

      {error && (
        <div className="bg-red-500/10 border border-red-500/50 text-red-400 rounded-md p-3 mb-4 text-sm">
          {error}
        </div>
      )}

      {success ? (
        <div className="bg-green-500/10 border border-green-500/50 text-green-400 rounded-md p-4 text-sm">
          <p className="font-medium mb-1">Check your email</p>
          <p>
            If an account exists with that email address, we&apos;ve sent a
            password reset link. Please check your inbox and spam folder.
          </p>
        </div>
      ) : (
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label htmlFor="email" className="block text-sm font-medium text-text-muted mb-1">
              Email
            </label>
            <input
              id="email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              className="w-full rounded-md border border-surface-light bg-background px-3 py-2 text-text placeholder-text-muted focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary"
              placeholder="your@email.com"
            />
          </div>

          <TurnstileWidget ref={turnstileRef} onVerify={setCaptchaToken} />

          <button
            type="submit"
            disabled={loading || !captchaToken}
            className="w-full rounded-md bg-primary py-2.5 text-white font-medium hover:bg-primary-dark focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 focus:ring-offset-background disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {loading ? "Sending..." : "Send Reset Link"}
          </button>
        </form>
      )}

      <p className="mt-6 text-center text-sm text-text-muted">
        Remember your password?{" "}
        <Link href="/login" className="text-primary hover:text-primary-dark font-medium">
          Sign In
        </Link>
      </p>
    </div>
  );
}
