"use client";

import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { otpSchema, type OTPFormData } from "@/features/auth/schemas/auth.schema";
import { useVerifySigninOTP } from "@/features/auth/hooks/useAuth";
import OTPInput from "./shared/OTPInput";
import ResendOTP from "./shared/ResendOTP";
import { useSendSigninOTP } from "@/features/auth/hooks/useAuth";

interface OTPVerificationModalProps {
  goSignin: () => void;
  onClose: () => void;
  onAuthSuccess: () => void;
  goSignup: () => void;
}

export default function OTPVerificationModal({
  goSignin,
  onClose,
  onAuthSuccess,
  goSignup,
}: OTPVerificationModalProps) {
  const [email, setEmail] = useState<string>("");
  const [otpSessionId, setOtpSessionId] = useState<string>("");
  const [timer, setTimer] = useState(60);
  const verifyOTPMutation = useVerifySigninOTP();
  const sendOTPMutation = useSendSigninOTP();

  const {
    setValue,
    watch,
    handleSubmit,
    formState: { errors },
    setError,
    clearErrors,
  } = useForm<OTPFormData>({
    resolver: zodResolver(otpSchema),
    defaultValues: {
      otp: "",
      email: "",
    },
  });

  const otp = watch("otp");

  // Get email and otpSessionId from sessionStorage (set by Signin when OTP was sent)
  useEffect(() => {
    if (typeof window !== "undefined") {
      const storedEmail = sessionStorage.getItem("signinEmail");
      const storedSessionId = sessionStorage.getItem("signinOtpSessionId");
      if (storedEmail) {
        setEmail(storedEmail);
        setValue("email", storedEmail);
      }
      if (storedSessionId) setOtpSessionId(storedSessionId);
    }
  }, [setValue]);

  // Timer countdown
  useEffect(() => {
    if (timer === 0) return;
    const interval = setInterval(() => setTimer((t) => t - 1), 1000);
    return () => clearInterval(interval);
  }, [timer]);

  const handleResendOTP = async () => {
    if (!email) return;
    try {
      setValue("otp", "");
      clearErrors();
      const result = await sendOTPMutation.mutateAsync({email,type:"signin"});
      const sessionId = result?.data?.otpSessionId;
      if (sessionId) {
        setOtpSessionId(sessionId);
        if (typeof window !== "undefined") sessionStorage.setItem("signinOtpSessionId", sessionId);
      }
      
      setTimer(60);
    } catch (error: unknown) {
      const msg =
        error && typeof error === "object" && "response" in error
          ? (error as { response?: { data?: { message?: string } } }).response?.data?.message
          : undefined;
      setError("otp", { message: msg || "Unable to resend OTP. Please try again." });
    }
  };

  const onSubmit = async (data: OTPFormData) => {
    if (!email) {
      setError("otp", { message: "Email not found. Please sign in again." });
      return;
    }
    if (!otpSessionId) {
      setError("otp", { message: "Session expired. Please request a new OTP from Sign in." });
      return;
    }

    try {
      clearErrors();
      await verifyOTPMutation.mutateAsync({
        email,
        otp: data.otp,
        otpSessionId: otpSessionId.trim(),
      });
      if (typeof window !== "undefined") {
        sessionStorage.removeItem("signinEmail");
        sessionStorage.removeItem("signinOtpSessionId");
      }
      onAuthSuccess();
    } catch (error: unknown) {
      const msg =
        error && typeof error === "object" && "response" in error
          ? (error as { response?: { data?: { message?: string } } }).response?.data?.message
          : undefined;
      setError("otp", { message: msg || "Invalid OTP. Please try again." });
    }
  };

  return (
    <section className="py-5 login-section w-100">
      <div className="container webNewContent">
        <div className="row justify-content-center">
          <div className="col-xxl-8 col-xl-8 col-lg-12 col-md-12 col-sm-12 col-12">
            <div className="row g-0 justify-content-center">
              <div className="col-xxl-8 col-xl-8 col-lg-8 col-md-10 col-sm-12 col-12 d-flex">
                <div className="card bgColor-white login-card rounded-2 shadow w-100 p-md-5 p-3 border-0">
                  <div className="card-body d-flex flex-column justify-content-center gap-2 p-0">
                    <h1 className="mainHeading font-heading">OTP Verification</h1>
                    <p>Enter the verification code we just sent on your email address</p>

                    <form className="booking-validation" noValidate onSubmit={handleSubmit(onSubmit)}>
                      <div className="row g-2">
                        <div className="col-12">
                          <OTPInput
                            value={otp}
                            onChange={(value) => setValue("otp", value)}
                            error={errors.otp?.message}
                            disabled={verifyOTPMutation.isPending}
                          />
                          <ResendOTP
                            timer={timer}
                            onResend={handleResendOTP}
                            loading={sendOTPMutation.isPending}
                          />
                        </div>

                        <div className="col-12">
                          <button
                            type="submit"
                            className="buttons btnColor-first rounded-2 py-2 w-100 submit-login-button ls-0"
                            disabled={!otp || otp.length !== 4 || verifyOTPMutation.isPending}
                          >
                            {verifyOTPMutation.isPending ? "Verifying..." : "Verify"}
                          </button>
                        </div>
                      </div>
                    </form>

                    <p className="text-center color-text-black text-sm">
                      Don&apos;t have account{" "}
                      <span onClick={goSignup} className="text-sm color-text-first fw-600 cursor-pointer">
                        Sign Up
                      </span>
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
