"use client";

import {
  type ClipboardEvent,
  type FormEvent,
  type KeyboardEvent,
  useEffect,
  useRef,
  useState,
} from "react";
import Link from "next/link";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { ArrowLeft, ArrowRight, Loader2, Mail } 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";

export default function ForgotPasswordPage() {
  const router = useRouter();
  const [email, setEmail] = useState("");
  const [error, setError] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [otpSent, setOtpSent] = useState(false);
  const [otp, setOtp] = useState(["", "", "", "", "", ""]);
  const [countdown, setCountdown] = useState(0);
  const [isVerifyingOtp, setIsVerifyingOtp] = useState(false);
  const otpInputRefs = useRef<Array<HTMLInputElement | null>>([]);

  const sendOtp = async () => {
    const trimmedEmail = email.trim();
    const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

    if (!trimmedEmail) {
      setError("Email address is required.");
      return;
    }

    if (!emailPattern.test(trimmedEmail)) {
      setError("Enter a valid email address.");
      return;
    }

    setError("");
    setIsSubmitting(true);

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

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

      if (!response.ok) {
        toast.error(getLocalizedApiMessage(result, "Unable to send OTP."));
        return;
      }

      toast.success(getLocalizedApiMessage(result, "OTP sent successfully."));
      setOtpSent(true);
      setOtp(["", "", "", "", "", ""]);
      setCountdown(21);
      window.setTimeout(() => otpInputRefs.current[0]?.focus(), 100);
    } catch {
      toast.error("Unable to connect to the OTP server.");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    await sendOtp();
  };

  const handleResendOtp = async () => {
    if (countdown > 0 || isSubmitting) return;
    await sendOtp();
  };

  const updateOtpValue = (index: number, value: string) => {
    const digit = value.replace(/\D/g, "").slice(-1);
    const nextOtp = [...otp];
    nextOtp[index] = digit;
    setOtp(nextOtp);

    if (digit && index < otp.length - 1) {
      otpInputRefs.current[index + 1]?.focus();
    }
  };

  const handleOtpKeyDown = (
    index: number,
    event: KeyboardEvent<HTMLInputElement>,
  ) => {
    if (event.key === "Backspace" && !otp[index] && index > 0) {
      otpInputRefs.current[index - 1]?.focus();
    }
  };

  const handleOtpPaste = (event: ClipboardEvent<HTMLInputElement>) => {
    event.preventDefault();
    const pastedOtp = event.clipboardData
      .getData("text")
      .replace(/\D/g, "")
      .slice(0, 6)
      .split("");
    const nextOtp = ["", "", "", "", "", ""];

    pastedOtp.forEach((digit, index) => {
      nextOtp[index] = digit;
    });

    setOtp(nextOtp);
    otpInputRefs.current[Math.min(pastedOtp.length, 5)]?.focus();
  };

  const handleVerifyOtp = async () => {
    const otpValue = otp.join("");

    if (otpValue.length !== 6) {
      toast.error("Please enter the 6 digit OTP.");
      return;
    }

    setIsVerifyingOtp(true);

    try {
      const response = await apiRequest(apiUrl("/verify-otp"), {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          email: email.trim(),
          otp: otpValue,
        }),
      });

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

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

      toast.success(
        getLocalizedApiMessage(result, "OTP verified successfully."),
      );
      setCountdown(0);
      router.push(
        `/auth/reset-password?email=${encodeURIComponent(email.trim())}`,
      );
    } catch {
      toast.error("Unable to connect to the OTP verification server.");
    } finally {
      setIsVerifyingOtp(false);
    }
  };

  useEffect(() => {
    if (!countdown) return;

    const timer = window.setTimeout(() => {
      setCountdown((value) => Math.max(value - 1, 0));
    }, 1000);

    return () => window.clearTimeout(timer);
  }, [countdown]);

  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/login"
                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 Login
              </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">
                  Forgot Password
                </h1>
                <p className="mt-2 leading-6 text-muted-foreground">
                  Enter your registered email address and we will send an OTP to
                  help you reset your password.
                </p>
              </div>

              <form onSubmit={handleSubmit} className="space-y-5" noValidate>
                <div className="space-y-2">
                  <Label htmlFor="forgot-email" className="text-sm font-medium">
                    Email Address
                  </Label>
                  <div className="relative">
                    <Mail className="absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                    <Input
                      id="forgot-email"
                      type="email"
                      value={email}
                      onChange={(event) => {
                        setEmail(event.target.value);
                        if (error) setError("");
                        if (otpSent) {
                          setOtpSent(false);
                          setOtp(["", "", "", "", "", ""]);
                          setCountdown(0);
                        }
                      }}
                      placeholder="example@domain.com"
                      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>
                  {error && (
                    <p className="text-xs font-semibold text-red-600">
                      {error}
                    </p>
                  )}
                </div>

                <Button
                  type="submit"
                  disabled={isSubmitting}
                  className="h-12 w-full rounded-xl border-0 bg-gradient-to-r from-[var(--theme-secondary)] to-[var(--theme-accent)] text-base font-medium text-white shadow-lg shadow-[var(--theme-secondary)]/20 hover:from-[var(--theme-primary)] hover:to-[var(--theme-primary-dark)]"
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Sending OTP
                    </>
                  ) : (
                    <>
                      Send OTP
                      <ArrowRight className="ml-2 h-4 w-4" />
                    </>
                  )}
                </Button>
              </form>

              {otpSent && (
                <div className="mt-7 space-y-5 border-t border-[var(--theme-border-soft)] pt-6">
                  <div>
                    <Button
                      type="button"
                      disabled={countdown > 0 || isSubmitting}
                      onClick={handleResendOtp}
                      className="h-12 w-full rounded-xl border-0 bg-[var(--theme-secondary)] text-base font-black text-white shadow-sm hover:bg-[var(--theme-primary)] disabled:opacity-75"
                    >
                      {countdown > 0
                        ? `Resend OTP in ${countdown}s`
                        : "Resend OTP"}
                    </Button>
                    <p className="mt-3 text-sm font-medium text-[var(--theme-primary)]">
                      OTP has been sent to your registered email address.
                    </p>
                  </div>

                  <div className="flex justify-between gap-2 sm:gap-3">
                    {otp.map((digit, index) => (
                      <Input
                        key={index}
                        ref={(element) => {
                          otpInputRefs.current[index] = element;
                        }}
                        value={digit}
                        onChange={(event) =>
                          updateOtpValue(index, event.target.value)
                        }
                        onKeyDown={(event) => handleOtpKeyDown(index, event)}
                        onPaste={handleOtpPaste}
                        inputMode="numeric"
                        maxLength={1}
                        aria-label={`OTP digit ${index + 1}`}
                        className="h-12 w-12 rounded-xl border-[var(--theme-border-strong)] bg-white p-0 text-center text-xl font-black focus:border-[var(--theme-primary)] focus:ring-[var(--theme-primary)]/20 sm:h-14 sm:w-14"
                      />
                    ))}
                  </div>

                  <Button
                    type="button"
                    onClick={handleVerifyOtp}
                    disabled={otp.join("").length !== 6 || isVerifyingOtp}
                    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)]"
                  >
                    {isVerifyingOtp ? (
                      <>
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        Verifying OTP
                      </>
                    ) : (
                      "Verify OTP"
                    )}
                  </Button>
                </div>
              )}
            </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">Recover access</span>
                <span className="block text-[var(--theme-primary)]">
                  with OTP
                </span>
                <span className="block text-4xl font-semibold text-foreground/60">
                  safely and quickly
                </span>
              </h2>
              <p className="mt-6 max-w-xl text-lg leading-8 text-foreground/80">
                Use the email linked with your guide account. We will verify the
                request before allowing any password change.
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
