"use client";

import { Suspense, type FormEvent, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { ArrowLeft, CheckCircle2, Loader2, Lock, XCircle } from "lucide-react";
import { toast } from "react-toastify";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { apiRequest, apiUrl } from "@/lib/api";
import { getLocalizedApiMessage } from "@/lib/api-message";

function ResetPasswordContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const email = searchParams.get("email") || "";
  const [password, setPassword] = useState("");
  const [passwordConfirmation, setPasswordConfirmation] = useState("");
  const [passwordError, setPasswordError] = useState("");
  const [isResettingPassword, setIsResettingPassword] = useState(false);

  const passwordRules = [
    {
      label: "At least 8 characters",
      passed: password.length >= 8,
    },
    {
      label: "Contains at least one number",
      passed: /\d/.test(password),
    },
    {
      label: "Password confirmation matches",
      passed: Boolean(password) && password === passwordConfirmation,
    },
  ];

  const passwordIsValid = passwordRules.every((rule) => rule.passed);

  const handleResetPassword = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (!email) {
      setPasswordError("Verified email is missing. Please verify OTP again.");
      return;
    }

    if (!passwordIsValid) {
      setPasswordError("Please complete the password requirements.");
      return;
    }

    setPasswordError("");
    setIsResettingPassword(true);

    try {
      const response = await apiRequest(apiUrl("/reset-password"), {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          email,
          password,
          password_confirmation: passwordConfirmation,
        }),
      });

      const result = await response.json().catch(() => ({}));

      if (!response.ok) {
        toast.error(getLocalizedApiMessage(result, "Password reset failed."));
        return;
      }

      toast.success(
        getLocalizedApiMessage(result, "Password reset successfully."),
      );
      router.push("/auth/login");
    } catch {
      toast.error("Unable to connect to the password reset server.");
    } finally {
      setIsResettingPassword(false);
    }
  };

  return (
    <div className="relative flex min-h-screen overflow-hidden pt-20">
      <Image
        src="https://images.unsplash.com/photo-1626621341517-bbf3d9990a23?w=1800&q=85"
        alt="Uttarakhand Mountains"
        fill
        className="object-cover"
        priority
      />
      <div className="absolute inset-0 bg-gradient-to-r from-background/90 via-background/68 to-background/35" />
      <div className="absolute inset-0 bg-gradient-to-t from-black/35 via-transparent to-white/10" />

      <div className="relative z-10 mx-auto flex w-full max-w-7xl items-center justify-center p-6 lg:p-10">
        <div className="grid w-full overflow-hidden rounded-[28px] bg-white/38 shadow-2xl shadow-black/10 backdrop-blur-md lg:grid-cols-2">
          <div className="flex items-center justify-center bg-white p-7 sm:p-10 lg:min-h-[620px] lg:p-14">
            <div className="w-full max-w-md">
              <Link
                href="/auth/forgot-password"
                className="mb-7 inline-flex items-center gap-2 text-sm font-semibold text-muted-foreground transition hover:text-[var(--theme-primary)]"
              >
                <ArrowLeft className="h-4 w-4" />
                Back to OTP
              </Link>

              <div className="mb-8">
                <p className="text-xs font-black uppercase tracking-wide text-[var(--theme-primary)]">
                  Account Recovery
                </p>
                <h1 className="mt-2 text-3xl font-bold text-foreground">
                  Reset Password
                </h1>
                <p className="mt-2 leading-6 text-muted-foreground">
                  Create a new password for{" "}
                  <span className="font-semibold text-foreground">
                    {email || "your verified email"}
                  </span>
                  .
                </p>
              </div>

              <form
                onSubmit={handleResetPassword}
                className="space-y-5"
                noValidate
              >
                <div className="space-y-2">
                  <Label htmlFor="new-password" className="text-sm font-medium">
                    New Password
                  </Label>
                  <div className="relative">
                    <Lock className="absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                    <Input
                      id="new-password"
                      type="password"
                      value={password}
                      onChange={(event) => {
                        setPassword(event.target.value);
                        if (passwordError) setPasswordError("");
                      }}
                      placeholder="Enter new password"
                      className="h-12 rounded-xl border-border/50 bg-white pl-11 focus:border-[var(--theme-primary)]/50 focus:ring-[var(--theme-primary)]/20"
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label
                    htmlFor="confirm-password"
                    className="text-sm font-medium"
                  >
                    Confirm Password
                  </Label>
                  <div className="relative">
                    <Lock className="absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                    <Input
                      id="confirm-password"
                      type="password"
                      value={passwordConfirmation}
                      onChange={(event) => {
                        setPasswordConfirmation(event.target.value);
                        if (passwordError) setPasswordError("");
                      }}
                      placeholder="Confirm new password"
                      className="h-12 rounded-xl border-border/50 bg-white pl-11 focus:border-[var(--theme-primary)]/50 focus:ring-[var(--theme-primary)]/20"
                    />
                  </div>
                </div>

                <div className="rounded-2xl border border-[var(--theme-border-soft)] bg-[var(--theme-surface)] p-4">
                  <p className="mb-3 text-sm font-black text-foreground">
                    Password Validation
                  </p>
                  <div className="space-y-2">
                    {passwordRules.map((rule) => (
                      <div
                        key={rule.label}
                        className={`flex items-center gap-2 text-sm font-semibold ${
                          rule.passed ? "text-emerald-700" : "text-slate-500"
                        }`}
                      >
                        {rule.passed ? (
                          <CheckCircle2 className="h-4 w-4" />
                        ) : (
                          <XCircle className="h-4 w-4" />
                        )}
                        {rule.label}
                      </div>
                    ))}
                  </div>
                </div>

                {passwordError && (
                  <p className="text-xs font-semibold text-red-600">
                    {passwordError}
                  </p>
                )}

                <Button
                  type="submit"
                  disabled={!passwordIsValid || isResettingPassword}
                  className="h-12 w-full rounded-xl border-0 bg-[var(--theme-primary)] text-base font-black text-white shadow-lg shadow-[var(--theme-primary)]/20 hover:bg-[var(--theme-primary-dark)]"
                >
                  {isResettingPassword ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Resetting Password
                    </>
                  ) : (
                    "Reset Password"
                  )}
                </Button>
              </form>
            </div>
          </div>

          <div className="hidden items-center border-l border-white/35 px-10 py-12 lg:flex xl:px-14">
            <div className="max-w-2xl">
              <div className="mb-6 inline-flex rounded-full border border-[var(--theme-secondary)]/25 bg-white/70 px-4 py-2 text-sm font-semibold text-[var(--theme-primary)] shadow-sm backdrop-blur-md">
                Secure Password Reset
              </div>
              <h2 className="text-5xl font-black leading-tight tracking-tight xl:text-6xl">
                <span className="block text-foreground">Set a stronger</span>
                <span className="block text-[var(--theme-primary)]">
                  password
                </span>
                <span className="block text-4xl font-semibold text-foreground/60">
                  for your account
                </span>
              </h2>
              <p className="mt-6 max-w-xl text-lg leading-8 text-foreground/80">
                Use a password that is easy for you to remember and difficult
                for others to guess.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function ResetPasswordPage() {
  return (
    <Suspense
      fallback={
        <div className="flex min-h-screen items-center justify-center bg-[var(--theme-surface)]">
          <div className="h-10 w-10 animate-spin rounded-full border-4 border-[var(--theme-secondary)]/25 border-t-[var(--theme-primary)]" />
        </div>
      }
    >
      <ResetPasswordContent />
    </Suspense>
  );
}
