"use client";

import { FormEvent, useState, useEffect, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { AlertMessage } from "@/components/ui/AlertMessage";
import { validatePassword, clearFieldError } from "@/utils/form-validation";
import { Eye, EyeOff, Loader2, Lock } from "lucide-react";

type FieldKey = "newPassword" | "confirmPassword";

function ResetPasswordForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const resetKey = searchParams.get("reset_key");

  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showNew, setShowNew] = useState(false);
  const [showConfirm, setShowConfirm] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<Partial<Record<FieldKey, string>>>({});
  const [loading, setLoading] = useState(false);
  const [validating, setValidating] = useState(true);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);
  const [tokenValid, setTokenValid] = useState(false);

  const clearError = (field: FieldKey) => {
    setFieldErrors((prev) => clearFieldError(prev, field));
  };

  useEffect(() => {
    if (!resetKey) {
      setErrorMsg("Missing reset token. Please check your email for the correct link.");
      setValidating(false);
      return;
    }

    // Validate the reset key
    fetch(`/api/reset-password?reset_key=${encodeURIComponent(resetKey)}`, {
      method: "GET",
      credentials: "include",
    })
      .then(async (res) => {
        if (!res.ok) {
          const data = await res.json().catch(() => ({}));
          throw new Error(data?.error || "Invalid or expired reset token");
        }
        const data = await res.json();
        if (data.status === "ready") {
          setTokenValid(true);
        } else {
          throw new Error("Invalid or expired reset token");
        }
      })
      .catch((err) => {
        setErrorMsg(err.message || "Failed to validate reset token");
      })
      .finally(() => {
        setValidating(false);
      });
  }, [resetKey]);

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setErrorMsg(null);
    setSuccessMsg(null);

    const errors: Partial<Record<FieldKey, string>> = {};

    const newError = validatePassword(newPassword, "New password");
    if (newError) errors.newPassword = newError;

    if (!confirmPassword) {
      errors.confirmPassword = "Confirm password is required.";
    } else if (newPassword !== confirmPassword) {
      errors.confirmPassword = "Passwords do not match.";
    }

    if (Object.keys(errors).length > 0) {
      setFieldErrors(errors);
      return;
    }

    setFieldErrors({});
    setLoading(true);

    try {
      const res = await fetch(`/api/reset-password?reset_key=${encodeURIComponent(resetKey!)}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
        body: JSON.stringify({ password: newPassword }),
      });

      const data = await res.json().catch(() => ({}));

      if (!res.ok) {
        setErrorMsg(data?.error || data?.message || "Failed to reset password. Please try again.");
        return;
      }

      if (data.status === "success") {
        setSuccessMsg("Password reset successfully. Redirecting to login...");
        setTimeout(() => {
          router.push("/login");
        }, 2000);
      } else {
        setErrorMsg("Failed to reset password. Please try again.");
      }
    } catch {
      setErrorMsg("Network error. Please try again.");
    } finally {
      setLoading(false);
    }
  }

  if (validating) {
    return (
      <div className="flex min-h-screen items-center justify-center">
        <div className="text-center">
          <Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
          <p className="text-slate-600">Validating reset token...</p>
        </div>
      </div>
    );
  }

  if (!tokenValid) {
    return (
      <div className="flex min-h-screen items-center justify-center px-4">
        <div className="w-full max-w-md">
          <div className="rounded-lg border border-red-200 bg-red-50 p-6 text-center">
            <Lock className="h-12 w-12 text-red-500 mx-auto mb-4" />
            <h1 className="text-xl font-semibold text-red-800 mb-2">Invalid Reset Link</h1>
            <p className="text-red-700">{errorMsg}</p>
            <Button
              onClick={() => router.push("/login")}
              className="mt-4"
            >
              Go to Login
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="flex min-h-screen items-center justify-center px-4 py-12">
      <div className="w-full max-w-md">
        <div className="rounded-lg border border-slate-200 bg-white p-6 shadow-sm">
          <div className="text-center mb-6">
            <Lock className="h-12 w-12 text-slate-600 mx-auto mb-4" />
            <h1 className="text-xl font-semibold text-slate-800">Reset Your Password</h1>
            <p className="text-slate-500 mt-1">Enter a new password for your account.</p>
          </div>

          {errorMsg && (
            <AlertMessage
              type="error"
              message={errorMsg}
              onDismiss={() => setErrorMsg(null)}
              className="animate-[fadeIn_0.3s_ease-in-out,slideDown_0.3s_ease-in-out]"
            />
          )}

          {successMsg && (
            <AlertMessage
              type="success"
              message={successMsg}
              className="animate-[fadeIn_0.3s_ease-in-out,slideDown_0.3s_ease-in-out]"
            />
          )}

          <form onSubmit={handleSubmit}>
            <FieldGroup>
              <Field>
                <FieldLabel htmlFor="new-password">New password</FieldLabel>
                <div className="relative">
                  <Input
                    id="new-password"
                    type={showNew ? "text" : "password"}
                    value={newPassword}
                    onChange={(e) => {
                      setNewPassword(e.target.value);
                      clearError("newPassword");
                    }}
                    placeholder="Enter new password"
                    className="pr-9"
                    autoComplete="new-password"
                    aria-invalid={!!fieldErrors.newPassword}
                  />
                  
                  <button
                    type="button"
                    onClick={() => setShowNew((s) => !s)}
                    className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
                    aria-label={showNew ? "Hide password" : "Show password"}
                  >
                    {showNew ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
                {fieldErrors.newPassword && (
                  <p className="text-destructive text-sm mt-1" role="alert">
                    {fieldErrors.newPassword}
                  </p>
                )}
                <p className="text-xs text-slate-500 mt-2">
                Password must contain at least 8 characters, including one uppercase letter,
                one lowercase letter, one number, and one special character.
                </p>
              </Field>

              <Field>
                <FieldLabel htmlFor="confirm-password">Confirm new password</FieldLabel>
                <div className="relative">
                  <Input
                    id="confirm-password"
                    type={showConfirm ? "text" : "password"}
                    value={confirmPassword}
                    onChange={(e) => {
                      setConfirmPassword(e.target.value);
                      clearError("confirmPassword");
                    }}
                    placeholder="Confirm new password"
                    className="pr-9"
                    autoComplete="new-password"
                    aria-invalid={!!fieldErrors.confirmPassword}
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirm((s) => !s)}
                    className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
                    aria-label={showConfirm ? "Hide password" : "Show password"}
                  >
                    {showConfirm ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
                {fieldErrors.confirmPassword && (
                  <p className="text-destructive text-sm mt-1" role="alert">
                    {fieldErrors.confirmPassword}
                  </p>
                )}
              </Field>

              <div className="pt-2">
                <Button type="submit" disabled={loading} className="w-full">
                  {loading ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin" />
                      Resetting…
                    </>
                  ) : (
                    "Reset Password"
                  )}
                </Button>
              </div>
            </FieldGroup>
          </form>
        </div>
      </div>
    </div>
  );
}

export default function ResetPasswordPage() {
  return (
    <Suspense fallback={
      <div className="flex min-h-screen items-center justify-center">
        <div className="text-center">
          <Loader2 className="h-8 w-8 animate-spin mx-auto mb-4" />
          <p className="text-slate-600">Loading...</p>
        </div>
      </div>
    }>
      <ResetPasswordForm />
    </Suspense>
  );
}