"use client";

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

const passwordChecks = [
  { label: "At least 8 characters", test: (value: string) => value.length >= 8 },
  { label: "At least 1 uppercase letter", test: (value: string) => /[A-Z]/.test(value) },
  { label: "At least 1 number", test: (value: string) => /\d/.test(value) },
  {
    label: "At least 1 special character",
    test: (value: string) => /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value),
  },
];

function ResetPasswordForm() {
  const searchParams = useSearchParams();
  const token = searchParams.get("token") || "";
  const [password, setPassword] = useState("");
  const [confirmation, setConfirmation] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isComplete, setIsComplete] = useState(false);
  const [error, setError] = useState("");
  const loginHref = "/login";

  const meetsRequirements = passwordChecks.every((check) => check.test(password));
  const canSubmit =
    Boolean(token) && meetsRequirements && confirmation === password && !isSubmitting;

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (password !== confirmation) {
      setError("The passwords do not match.");
      return;
    }

    setIsSubmitting(true);
    setError("");
    try {
      const response = await fetch("/api/auth/reset-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, password }),
      });
      const text = await response.text();
      let payload: { error?: string } = {};
      try {
        if (text && text.trim()) payload = JSON.parse(text) as { error?: string };
      } catch {
        // Non-JSON fallback
      }
      if (!response.ok) throw new Error(payload.error || "Unable to reset password.");
      try {
        sessionStorage.removeItem("roosports_reset_email");
      } catch {
        // Ignore storage errors.
      }
      setIsComplete(true);
    } catch (requestError) {
      setError(
        requestError instanceof Error
          ? requestError.message
          : "Unable to reset password.",
      );
    } 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-14 lg:grid-cols-[0.9fr_1.1fr] lg:items-center lg:gap-20 lg:px-16">
      <section className="max-w-xl">
        <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]" />
          Secure reset
        </p>
        <h1 className="text-5xl font-extrabold leading-[0.96] tracking-[-0.055em] sm:text-6xl lg:text-7xl">
          A fresh start, securely.
        </h1>
        <p className="mt-7 max-w-lg text-base leading-7 text-[#5c6970] md:text-lg">
          Choose a password that is difficult to guess and different from passwords
          you use elsewhere.
        </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" />

        {isComplete ? (
          <div className="relative flex min-h-[470px] flex-col justify-between">
            <div>
              <h2 className="text-4xl font-extrabold leading-tight tracking-[-0.045em]">
                Password updated.
              </h2>
              <p className="mt-4 max-w-md text-sm leading-7 text-[#647179]">
                Your old sessions have been signed out. Log in again with your new
                password to continue.
              </p>
            </div>
            <Link
              href={loginHref}
            className="rs-primary-action flex w-full items-center justify-between rounded-full px-6 py-4 text-sm font-bold"
            >
              Continue to login
              <span className="flex h-9 w-9 items-center justify-center rounded-full bg-white">
                <span className="material-symbols-outlined">arrow_forward</span>
              </span>
            </Link>
          </div>
        ) : !token ? (
          <div className="relative flex min-h-[470px] flex-col justify-between">
            <div>
              <span className="flex h-14 w-14 items-center justify-center rounded-full bg-[#ffe4d7] text-[#a23b16]">
                <span className="material-symbols-outlined text-3xl">link_off</span>
              </span>
              <h2 className="mt-8 text-4xl font-extrabold leading-tight tracking-[-0.045em]">
                This link is incomplete.
              </h2>
              <p className="mt-4 max-w-md text-sm leading-7 text-[#647179]">
                Request a new password reset email to receive a complete, secure link.
              </p>
            </div>
            <Link
              href="/forgot-password"
              className="rs-primary-action flex w-full items-center justify-between rounded-full px-6 py-4 text-sm font-bold"
            >
              Request a new link
              <span className="material-symbols-outlined">arrow_forward</span>
            </Link>
          </div>
        ) : (
          <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">
              New password
            </span>
            <h2 className="mt-8 text-3xl font-extrabold leading-tight tracking-[-0.04em] sm:text-4xl">
              Make it strong and memorable.
            </h2>

            <form onSubmit={handleSubmit} className="mt-8 space-y-6">
              <div>
                <label
                  htmlFor="new-password"
                  className="text-[11px] font-bold uppercase tracking-[0.16em] text-[#5c6970]"
                >
                  New password
                </label>
                <div className="relative mt-2">
                  <input
                    id="new-password"
                    type={showPassword ? "text" : "password"}
                    required
                    autoComplete="new-password"
                    value={password}
                    onChange={(event) => setPassword(event.target.value)}
                    className="rs-field w-full rounded-2xl py-3.5 pl-4 pr-12 text-base"
                  />
                  <button
                    type="button"
                    aria-label={showPassword ? "Hide password" : "Show password"}
                    onClick={() => setShowPassword((current) => !current)}
                    className="absolute right-0 top-1/2 -translate-y-1/2 text-[#647179]"
                  >
                    <span className="material-symbols-outlined">
                      {showPassword ? "visibility_off" : "visibility"}
                    </span>
                  </button>
                </div>
              </div>

              <div>
                <label
                  htmlFor="confirm-password"
                  className="text-[11px] font-bold uppercase tracking-[0.16em] text-[#5c6970]"
                >
                  Confirm password
                </label>
                <input
                  id="confirm-password"
                  type={showPassword ? "text" : "password"}
                  required
                  autoComplete="new-password"
                  value={confirmation}
                  onChange={(event) => setConfirmation(event.target.value)}
                  className="rs-field mt-2 w-full rounded-2xl px-4 py-3.5 text-base"
                />
              </div>

              <ul className="grid grid-cols-1 gap-2 sm:grid-cols-2">
                {passwordChecks.map((check) => {
                  const isMet = check.test(password);
                  return (
                    <li
                      key={check.label}
                      className={`flex items-center gap-2 text-xs ${
                        isMet ? "font-medium text-[#197344]" : "text-[#748087]"
                      }`}
                    >
                      <span className="material-symbols-outlined text-base">
                        {isMet ? "check_circle" : "radio_button_unchecked"}
                      </span>
                      {check.label}
                    </li>
                  );
                })}
              </ul>

              {confirmation && confirmation !== password && (
                <p className="rounded-xl bg-[#f8e2df]/80 px-4 py-3 text-sm font-medium text-[#9a4338]">The passwords do not match.</p>
              )}
              {error && (
                <p role="alert" aria-live="polite" className="rounded-xl bg-[#f8e2df]/80 px-4 py-3 text-sm font-medium text-[#9a4338]">
                  {error}
                </p>
              )}

              <button
                type="submit"
                disabled={!canSubmit}
                className="rs-primary-action 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 ? "Updating securely..." : "Update password"}</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>
        )}
      </section>
    </main>
  );
}

export default function ResetPasswordPage() {
  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]" />}>
        <ResetPasswordForm />
      </Suspense>
    </div>
  );
}
