"use client";

import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { Suspense, useState } from "react";
import { RooSportsLogo } from "@/components/roosports-logo";

type ForgotPasswordResponse = {
  message?: string;
  error?: string;
  previewUrl?: string;
};

const heroTitleClass =
  "text-[2.35rem] font-extrabold leading-none tracking-[-0.055em] sm:text-5xl lg:text-[3.35rem] lg:leading-[1.02] xl:text-[3.75rem]";

export default function ForgotPasswordPage() {
  return (
    <div className="rs-page-surface min-h-screen">
      <header className="mx-auto flex w-full max-w-7xl items-center justify-between px-6 py-7 md:px-12 lg:px-16">
        <Link
          href="/"
          aria-label="RooSports home"
          className="text-3xl text-[#0b0f12] transition-opacity hover:opacity-70 md:text-4xl"
        >
          <RooSportsLogo />
        </Link>
        <Link
          href="/login"
          className="flex items-center gap-2 rounded-full bg-white/50 px-5 py-3 text-xs font-bold uppercase tracking-[0.13em] backdrop-blur-xl transition-transform hover:-translate-y-0.5"
        >
          Back to login
          <span className="material-symbols-outlined text-lg">arrow_forward</span>
        </Link>
      </header>

      <Suspense fallback={<div className="min-h-[60vh]" />}>
        <ForgotPasswordForm />
      </Suspense>
    </div>
  );
}

function ForgotPasswordForm() {
  const searchParams = useSearchParams();
  const [email, setEmail] = useState(() => searchParams.get("email")?.trim() || "");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSent, setIsSent] = useState(false);
  const [error, setError] = useState("");
  const [previewUrl, setPreviewUrl] = useState("");

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setIsSubmitting(true);
    setError("");

    try {
      const response = await fetch("/api/auth/forgot-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      const text = await response.text();
      let payload: ForgotPasswordResponse = {};
      try {
        if (text && text.trim()) payload = JSON.parse(text) as ForgotPasswordResponse;
      } catch {
        // Non-JSON fallback
      }
      if (!response.ok) throw new Error(payload.error || "Unable to send reset link.");

      setPreviewUrl(payload.previewUrl || "");
      try {
        sessionStorage.setItem("roosports_reset_email", email.trim().toLowerCase());
      } catch {
        // Ignore storage errors.
      }
      setIsSent(true);
    } catch (requestError) {
      setError(
        requestError instanceof Error
          ? requestError.message
          : "Unable to send reset link.",
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
      <main className="mx-auto grid w-full max-w-7xl gap-10 px-6 pb-16 pt-8 md:px-12 md:pt-16 lg:grid-cols-[1.05fr_0.95fr] lg:items-center lg:gap-20 lg:px-16">
        <section className="min-w-0 max-w-xl lg:max-w-none">
          <p className="mb-5 flex items-center gap-3 text-xs font-bold uppercase tracking-[0.2em] text-[#5c6970]">
            <span className="h-2.5 w-2.5 rounded-full bg-[#ef7d00]" />
            Account recovery
          </p>
          {isSent ? (
            <>
              <h1 className={heroTitleClass}>
                Link sent.
              </h1>
              <p className="mt-7 max-w-lg text-base leading-7 text-[#5c6970] md:text-lg">
                If an account exists for your email, a secure reset link is on its way.
                Open it within 30 minutes to choose a new password.
              </p>
            </>
          ) : (
            <>
              <h1 className={`${heroTitleClass} lg:whitespace-nowrap`}>
                Get back in the game.
              </h1>
              <p className="mt-7 max-w-lg text-base leading-7 text-[#5c6970] md:text-lg">
                Enter the email linked to your RooSports account. We will send a secure
                link so you can choose a new password.
              </p>
            </>
          )}

          <p className="mt-10 text-sm leading-6 text-[#5c6970]">
            Reset links are sent by email, expire after 30 minutes, and can only be used once.
          </p>
        </section>

        <section className="rs-soft-panel relative overflow-hidden rounded-[2.5rem] border border-white/60 p-7 sm:p-10">
          <div className="absolute -right-20 -top-20 h-52 w-52 rounded-full bg-[#ffd16e]/60" />
          <div className="absolute -right-6 -top-6 h-28 w-28 rounded-full border-[22px] border-white/45" />

          {!isSent ? (
            <div className="relative">
              <span className="inline-flex rounded-full bg-[#0B0F12] px-4 py-2 text-[11px] font-bold uppercase tracking-[0.16em] text-white">
                Reset password
              </span>
              <h2 className="mt-8 max-w-sm text-3xl font-extrabold leading-tight tracking-[-0.04em] sm:text-4xl">
                Where should we send your link?
              </h2>
              <p className="mt-4 max-w-md text-sm leading-6 text-[#647179]">
                For your privacy, the confirmation looks the same whether an account
                exists or not.
              </p>

              <form onSubmit={handleSubmit} className="mt-10">
                <label
                  htmlFor="reset-email"
                  className="text-[11px] font-bold uppercase tracking-[0.16em] text-[#5c6970]"
                >
                  Email address
                </label>
                <input
                  id="reset-email"
                  type="email"
                  required
                  autoComplete="email"
                  maxLength={255}
                  value={email}
                  onChange={(event) => setEmail(event.target.value)}
                  placeholder="your@email.com"
                  className="rs-field mt-3 w-full rounded-2xl px-4 py-3.5 text-base placeholder:text-[#879299]"
                />

                {error && (
                  <p role="alert" aria-live="polite" className="mt-4 rounded-xl bg-[#f8e2df]/80 px-4 py-3 text-sm font-medium text-[#9a4338]">
                    {error}
                  </p>
                )}

                <button
                  type="submit"
                  disabled={isSubmitting || !email.trim()}
                  className="rs-primary-action mt-9 flex w-full items-center justify-between rounded-full px-6 py-4 text-sm font-bold disabled:translate-y-0 disabled:cursor-not-allowed disabled:opacity-45 disabled:shadow-none"
                >
                  <span>{isSubmitting ? "Sending securely..." : "Send reset link"}</span>
                  <span className="flex h-9 w-9 items-center justify-center rounded-full bg-white">
                    <span className="material-symbols-outlined">arrow_forward</span>
                  </span>
                </button>
              </form>
            </div>
          ) : (
            <div className="relative flex min-h-[430px] flex-col justify-between">
              <div>
                <h2 className="text-4xl font-extrabold leading-tight tracking-[-0.045em]">
                  Check your inbox.
                </h2>
                <p className="mt-4 max-w-md text-sm leading-7 text-[#647179]">
                  If an account matches this email, a reset link is on its way.
                </p>
                <p className="mt-3 inline-flex max-w-full truncate rounded-full bg-[#eff5f7] px-4 py-2 text-sm font-bold text-[#0B0F12]">{email}</p>
                <p className="mt-2 max-w-md text-sm leading-7 text-[#647179]">
                  Check your spam folder if it does not arrive.
                </p>
              </div>

              <div className="space-y-3">
                {previewUrl && (
                  <div className="rounded-2xl border border-[#ef7d00]/25 bg-[#fff8ee] p-4">
                    <p className="text-[11px] font-bold uppercase tracking-[0.14em] text-[#a85600]">
                      Development test only
                    </p>
                    <p className="mt-2 text-xs leading-5 text-[#647179]">
                      SMTP is not configured locally. Use the button below to test the reset
                      flow — this will not appear in production.
                    </p>
                    <a
                      href={previewUrl}
                      className="rs-primary-action mt-4 flex w-full items-center justify-between rounded-full px-6 py-4 text-sm font-bold"
                    >
                      Open test reset link
                      <span className="material-symbols-outlined">open_in_new</span>
                    </a>
                  </div>
                )}
                <button
                  type="button"
                  onClick={() => {
                    setIsSent(false);
                    setPreviewUrl("");
                  }}
                  className="w-full rounded-full border border-[#d6e2e6] bg-white/70 px-6 py-4 text-sm font-bold transition-colors hover:bg-white"
                >
                  Try another email
                </button>
              </div>
            </div>
          )}
        </section>
      </main>
  );
}
