"use client";

import dynamic from "next/dynamic";
import Link from "next/link";
import { useState } from "react";

function ForgotPasswordPage() {
  const [usernameOrEmail, setUsernameOrEmail] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [submitted, setSubmitted] = useState(false);

  async function handleSubmit(e) {
    e.preventDefault();
    setError("");
    setMessage("");
    setLoading(true);

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

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.message || "Something went wrong. Please try again.");
      }

      setMessage(data.message || "If an account matches, a reset link has been sent to your email.");
      setSubmitted(true);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <main className="auth-page">
      <div className="auth-card">
        <h1 className="auth-title">Forgot Password</h1>

        {!submitted ? (
          <>
            <p style={{ color: "#6b7280", marginBottom: "1.25rem", fontSize: "0.95rem" }}>
              Enter your username or email address and we&apos;ll send you a link to reset your password.
            </p>

            {error && <p className="auth-error">{error}</p>}

            <form className="auth-form" onSubmit={handleSubmit}>
              <label className="auth-label">
                Username or Email
                <input
                  className="auth-input"
                  type="text"
                  value={usernameOrEmail}
                  onChange={(e) => setUsernameOrEmail(e.target.value)}
                  required
                  autoComplete="username"
                />
              </label>

              <button className="auth-submit-btn" type="submit" disabled={loading}>
                {loading ? "Sending…" : "Send Reset Link"}
              </button>
            </form>
          </>
        ) : (
          <p style={{ color: "#16a34a", margin: "1rem 0", lineHeight: 1.6 }}>{message}</p>
        )}

        <p className="auth-switch">
          Remember your password?{" "}
          <Link href="/login" className="auth-switch-link">Log in here</Link>
        </p>
        <p className="auth-switch">
          Don&apos;t have an account?{" "}
          <Link href="/register" className="auth-switch-link">Register here</Link>
        </p>
      </div>
    </main>
  );
}

export default dynamic(() => Promise.resolve(ForgotPasswordPage), {
  ssr: false,
});
