"use client";

import dynamic from "next/dynamic";
import Link from "next/link";
import { useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";

const labelCls = "flex flex-col gap-[0.35rem] text-[0.9rem] font-semibold text-[#444]";
const inputCls = "px-[0.85rem] py-[0.6rem] border border-[#ddd] rounded-lg text-base outline-none transition-all focus:border-[#e68672] focus:shadow-[0_0_0_3px_rgba(230,134,114,0.2)]";
const submitBtnCls = "mt-2 py-3 bg-[#e68672] text-white border-none rounded-lg text-base font-bold cursor-pointer transition-all hover:bg-[#d4705e] active:scale-[0.98] disabled:opacity-60 disabled:cursor-not-allowed";

//Reset password page, reads the token from the URL and lets the user set a new password
function ResetPasswordPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const token = searchParams.get("token") || "";

  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);

  if (!token) {
    return (
      <main className="min-h-[calc(100vh-70px)] flex items-center justify-center py-8 px-4 bg-[#fafafa]">
        <div className="bg-white rounded-2xl shadow-[0_4px_24px_rgba(0,0,0,0.1)] p-10 w-full max-w-[440px] max-[480px]:p-6">
          <h1 className="text-[1.75rem] font-bold text-[#222] m-0 mb-6 text-center">Invalid Link</h1>
          <p className="bg-[#fff0f0] border border-[#f5c6c6] text-[#c0392b] rounded-lg px-4 py-[0.65rem] text-[0.9rem] mb-2">
            This password reset link is missing or invalid. Please request a new one.
          </p>
          <p className="text-center text-[0.9rem] text-[#666] mt-5">
            <Link href="/forgot-password" className="text-[#e68672] font-semibold no-underline hover:underline">Request a new reset link</Link>
          </p>
        </div>
      </main>
    );
  }

  //Validates passwords match, submits the reset, then redirects to login after 3 seconds
  async function handleSubmit(e) {
    e.preventDefault();
    setError("");

    if (newPassword !== confirmPassword) {
      setError("Passwords do not match.");
      return;
    }

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

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.message || "Failed to reset password. The link may have expired.");
      }

      setSuccess(true);
      setTimeout(() => router.push("/login"), 3000);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  if (success) {
    return (
      <main className="min-h-[calc(100vh-70px)] flex items-center justify-center py-8 px-4 bg-[#fafafa]">
        <div className="bg-white rounded-2xl shadow-[0_4px_24px_rgba(0,0,0,0.1)] p-10 w-full max-w-[440px] max-[480px]:p-6">
          <h1 className="text-[1.75rem] font-bold text-[#222] m-0 mb-6 text-center">Password Reset</h1>
          <p className="text-[#16a34a] my-4 leading-relaxed">
            Your password has been reset successfully. Redirecting you to login…
          </p>
          <p className="text-center text-[0.9rem] text-[#666] mt-5">
            <Link href="/login" className="text-[#e68672] font-semibold no-underline hover:underline">Go to login</Link>
          </p>
        </div>
      </main>
    );
  }

  return (
    <main className="min-h-[calc(100vh-70px)] flex items-center justify-center py-8 px-4 bg-[#fafafa]">
      <div className="bg-white rounded-2xl shadow-[0_4px_24px_rgba(0,0,0,0.1)] p-10 w-full max-w-[440px] max-[480px]:p-6">
        <h1 className="text-[1.75rem] font-bold text-[#222] m-0 mb-6 text-center">Reset Password</h1>

        {error && <p className="bg-[#fff0f0] border border-[#f5c6c6] text-[#c0392b] rounded-lg px-4 py-[0.65rem] text-[0.9rem] mb-2">{error}</p>}

        <form className="flex flex-col gap-4" onSubmit={handleSubmit}>
          <label className={labelCls}>
            New Password
            <input className={inputCls} type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} required minLength={6} autoComplete="new-password" />
          </label>

          <label className={labelCls}>
            Confirm New Password
            <input className={inputCls} type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} required autoComplete="new-password" />
          </label>

          <button className={submitBtnCls} type="submit" disabled={loading}>
            {loading ? "Resetting…" : "Reset Password"}
          </button>
        </form>

        <p className="text-center text-[0.9rem] text-[#666] mt-5">
          Remember your password?{" "}
          <Link href="/login" className="text-[#e68672] font-semibold no-underline hover:underline">Log in here</Link>
        </p>
      </div>
    </main>
  );
}

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