"use client";

import { useState, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { ApiError, apiFetch } from "@/lib/apiClient";

function ResetPasswordForm() {
  const router = useRouter();
  const params = useSearchParams();
  const token = params.get("token") ?? "";

  const [form, setForm] = useState({ password: "", confirm: "" });
  const [showPass, setShowPass] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  const [done, setDone] = useState(false);

  const set = (field: string) => (e: React.ChangeEvent<HTMLInputElement>) =>
    setForm((f) => ({ ...f, [field]: e.target.value }));

  const strength = (() => {
    const p = form.password;
    let score = 0;
    if (p.length >= 8) score++;
    if (/[A-Z]/.test(p)) score++;
    if (/[0-9]/.test(p)) score++;
    if (/[^A-Za-z0-9]/.test(p)) score++;
    return score;
  })();
  const strengthLabel = ["", "Weak", "Fair", "Good", "Strong"][strength];
  const strengthColor = ["", "#ba1a1a", "#FED665", "#4f57a6", "#755b00"][strength];

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    if (form.password !== form.confirm) { setError("Passwords do not match"); return; }
    if (strength < 2) { setError("Password is too weak — add uppercase, numbers, or symbols"); return; }
    if (!token) { setError("Invalid reset link — request a new one"); return; }
    setLoading(true);
    try {
      await apiFetch("/auth/reset-password", {
        method: "POST",
        body: JSON.stringify({ token, password: form.password }),
        skipAuth: true,
      });
      setDone(true);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "Reset failed");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="bg-visionary-gradient min-h-screen flex items-center justify-center p-6 overflow-x-hidden">
      <div className="fixed inset-0 pointer-events-none overflow-hidden">
        <div className="absolute -top-1/4 -right-1/4 w-[600px] h-[600px] bg-[#FED665] opacity-5 blur-[120px] rounded-full" />
        <div className="absolute -bottom-1/4 -left-1/4 w-[600px] h-[600px] bg-[#040b61] opacity-20 blur-[120px] rounded-full" />
      </div>

      <section className="auth-glass-login rounded-3xl p-8 md:p-12 w-full max-w-[480px] shadow-[0_32px_64px_-12px_rgba(1,7,95,0.2)] z-10">
        {done ? (
          <div className="text-center">
            <div className="w-20 h-20 bg-[#755B00] rounded-full flex items-center justify-center mb-6 mx-auto">
              <span className="material-symbols-outlined text-[#FED665] text-4xl" style={{ fontVariationSettings: "'FILL' 1" }}>check_circle</span>
            </div>
            <h2 className="font-headline-md text-headline-md text-[#040b61] mb-2">Password Updated!</h2>
            <p className="text-[#464651] text-sm mb-8">Your password has been changed successfully.</p>
            <Link href="/login"
              className="bg-[#040b61] text-white px-8 py-3 rounded-full font-semibold text-[14px] hover:bg-[#0D1145] transition-all inline-block">
              Sign In Now
            </Link>
          </div>
        ) : (
          <>
            <div className="flex flex-col items-center mb-8">
              <span className="inline-block bg-[#fed979] text-[#785d03] px-4 py-1.5 rounded-full text-[14px] font-semibold mb-4 uppercase tracking-widest">
                Almost There
              </span>
              <h1 className="font-headline-md text-headline-md text-center text-[#040b61]">
                Create a New Password
              </h1>
            </div>

            {error && (
              <div className="mb-5 p-3 rounded-xl bg-red-50 border border-red-200 text-red-600 text-sm">
                {error}
              </div>
            )}

            <form onSubmit={handleSubmit} className="space-y-5">
              <div className="relative">
                <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#464651]">lock</span>
                <input
                  type={showPass ? "text" : "password"} required minLength={8}
                  placeholder="New Password"
                  value={form.password} onChange={set("password")}
                  className="w-full pl-12 pr-12 py-4 bg-[#f3f3f3] border border-[#c6c5d3] rounded-xl focus:ring-2 focus:ring-[#FED665] focus:border-transparent outline-none transition-all placeholder:text-[#767682]"
                />
                <button type="button" onClick={() => setShowPass(!showPass)}
                  className="absolute right-4 top-1/2 -translate-y-1/2 text-[#464651] hover:text-[#1a1c1c]">
                  <span className="material-symbols-outlined">{showPass ? "visibility_off" : "visibility"}</span>
                </button>
                {form.password.length > 0 && (
                  <div className="mt-2 px-1">
                    <div className="flex gap-1">
                      {[1, 2, 3, 4].map((i) => (
                        <div key={i} className="flex-1 h-1 rounded-full transition-all"
                          style={{ background: i <= strength ? strengthColor : "#e2e2e2" }} />
                      ))}
                    </div>
                    <p className="text-xs mt-1" style={{ color: strengthColor }}>{strengthLabel}</p>
                  </div>
                )}
              </div>

              <div className="relative">
                <span className="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-[#464651]">lock_reset</span>
                <input
                  type={showPass ? "text" : "password"} required
                  placeholder="Confirm New Password"
                  value={form.confirm} onChange={set("confirm")}
                  className="w-full pl-12 pr-4 py-4 bg-[#f3f3f3] border border-[#c6c5d3] rounded-xl focus:ring-2 focus:ring-[#FED665] focus:border-transparent outline-none transition-all placeholder:text-[#767682]"
                />
              </div>

              <button
                type="submit" disabled={loading}
                className="w-full bg-[#040b61] text-white py-4 rounded-full font-semibold text-[14px] flex items-center justify-center gap-2 hover:bg-[#0D1145] transition-all active:scale-95 shadow-lg disabled:opacity-60"
              >
                {loading ? "Resetting..." : "Reset Password"}
                {!loading && <span className="material-symbols-outlined text-[20px]">check_circle</span>}
              </button>
            </form>

            <div className="mt-6 text-center">
              <Link href="/login" className="text-[#464651] text-sm hover:text-[#040b61] transition-colors">
                ← Back to Sign In
              </Link>
            </div>
          </>
        )}
      </section>
    </div>
  );
}

export default function ResetPasswordPage() {
  return (
    <Suspense>
      <ResetPasswordForm />
    </Suspense>
  );
}
