"use client";

import { useState, useEffect } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { signupSchema, type SignupFormData } from "@/features/auth/schemas/auth.schema";
import { useSendSignupOTP, useCompleteSignup } from "@/features/auth/hooks/useAuth";
import AuthCarousel from "./shared/AuthCarousel";
import SocialAuthButtons from "./shared/SocialAuthButtons";
import ResendOTP from "./shared/ResendOTP";
import Link from "next/link";
import { executeRecaptcha, loadRecaptchaScript } from "@/utils/recaptcha";
import { Pencil } from "lucide-react";

interface SignupModalProps {
  goSignin: () => void;
  onClose: () => void;
  onAuthSuccess: () => void;
  slides: { src: string, title?: string, subtitle?: string }[];
}

export default function SignupModal({ goSignin, onClose, onAuthSuccess, slides }: SignupModalProps) {
  const [socialError, setSocialError] = useState<string | null>(null);
  const [otpSent, setOtpSent] = useState(false);
  const [otpSessionId, setOtpSessionId] = useState<string>("");
  const [timer, setTimer] = useState(0);
  const [isEditingEmail, setIsEditingEmail] = useState(false);
  const [smsConsent, setSmsConsent] = useState(true);
  const sendOTPMutation = useSendSignupOTP();
  const completeSignupMutation = useCompleteSignup();

  // Load reCAPTCHA script on component mount
  useEffect(() => {
    loadRecaptchaScript().catch((error) => {
      console.error("Failed to load reCAPTCHA script:", error);
    });
  }, []);

  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
    setError,
    clearErrors,
  } = useForm<SignupFormData>({
    resolver: zodResolver(signupSchema),
    mode: "onChange",
    defaultValues: {
      fullName: "",
      email: "",
      otp: "",
    },
  });

  const email = watch("email");
  const otp = watch("otp");

  // Check if email is valid
  const isEmailValid = email && !errors.email;

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

  const handleSendOTP = async () => {
    if (!email) {
      setError("email", { message: "Email is required" });
      return;
    }
    try {
      setSocialError(null);
      clearErrors();
      const result = await sendOTPMutation.mutateAsync({email,type:"signup"});
      const sessionId = result?.data?.otpSessionId;
      if (sessionId) setOtpSessionId(sessionId);
      setOtpSent(true);
      setTimer(60);
    } catch (error: unknown) {
      const errorMessage =
        error && typeof error === "object" && "response" in error
          ? (error as { response?: { data?: { message?: string } } }).response?.data?.message
          : undefined;
      setError("email", {
        message: errorMessage || "Unable to send OTP. Please try again.",
      });
    }
  };

  const handleResendOTP = async () => {
    await handleSendOTP();
  };
  const onSubmit = async (data: SignupFormData) => {
    if (!otpSent) {
      await handleSendOTP();
      return;
    }

    if (!otpSessionId) {
      setError("otp", { message: "Session expired. Please request a new OTP." });
      return;
    }

    try {
      let recaptchaToken: string;

      try {
        recaptchaToken = await executeRecaptcha("signup");
      } catch (err) {
        console.error("reCAPTCHA error:", err);
        setError("otp", {
          message: "Security verification failed. Please refresh and try again.",
        });
        return;
      }

      await completeSignupMutation.mutateAsync(
        {
          fullName: data.fullName,
          email: data.email,
          otp: data.otp,
          otpSessionId,
          recaptchaToken,
          smsRcsMarketingConsent: smsConsent
        },

      );

      onAuthSuccess();
    } catch (error: unknown) {
      const err = error as { response?: { data?: { message?: string; error?: { message?: string } } }; message?: string };
      const errorMessage =
        err?.response?.data?.error?.message ??
        err?.response?.data?.message ??
        err?.message ??
        "Invalid OTP or signup failed. Please try again.";
      setError("otp", { message: errorMessage });
    }
  };

  const handleBackdropClick = (e: React.MouseEvent<HTMLElement>) => {
    // Close modal when clicking on section background, not on card content
    if (e.target === e.currentTarget) {
      onClose();
    }
  };
  console.log(otpSent)

  return (
    <section className="py-5 login-section w-100" onClick={handleBackdropClick}>
      <div className="container webNewContent" onClick={handleBackdropClick}>
        <div className="row justify-content-center" onClick={handleBackdropClick}>
          <div className="col-xxl-8 col-xl-8 col-lg-8 col-md-8 col-sm-12 col-12" onClick={handleBackdropClick}>
            <div className="d-flex g-0 justify-content-center  " onClick={handleBackdropClick}>
              
              <AuthCarousel slides={slides} />
              

              <div className=" col-12 col-md-6 d-flex gap-2">
                <div className="card bgColor-white login-card 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">Welcome Back!
                    Glad to see you, again!</h1>

                    <form className="booking-validation" noValidate onSubmit={handleSubmit(onSubmit)}>
                      <div className="row g-3">
                        <div className="col-12">
                          <label className="text-black text-sm">Full Name</label>
                          <input
                            type="text"
                            className={`form-control border rounded ${errors.fullName ? "is-invalid" : ""}`}
                            placeholder="Enter Full Name"
                            {...register("fullName")}
                          />
                          {errors.fullName && (
                            <div className="invalid-feedback d-block">{errors.fullName.message}</div>
                          )}
                        </div>
                        <div className="col-12 position-relative ">
                          <label className="text-black text-sm">Email</label>

                          <input
                            type="email"
                            className={`form-control rounded-2 border ${errors.email ? "is-invalid" : ""}`}
                            placeholder="Enter Email Address"
                            {...register("email")}
                            disabled={otpSent && !isEditingEmail}
                          />

                          {/* Edit Icon */}
                          {otpSent && !isEditingEmail && (
                            <span className=""
                              onClick={() => {
                                setIsEditingEmail(true);
                                setOtpSent(false);
                                setOtpSessionId("");
                                setTimer(0);
                              }}
                              style={{
                                position: "absolute",
                                right: "15px",
                                top: "35px",
                                cursor: "pointer",
                                fontSize: "14px",
                              }}
                            >
                              <Pencil size={20}/>
                            </span>
                          )}

                          {errors.email && (
                            <div className="invalid-feedback d-block">{errors.email.message}</div>
                          )}
                        </div>


                        <div className="col-12">
                          <label className="text-black text-sm">OTP</label>
                          <input
                            type="text"
                            className={`form-control border rounded ${errors.otp ? "is-invalid" : ""}`}
                            placeholder="Verification Code"
                            {...register("otp")}
                            disabled={!otpSent}
                            maxLength={4}
                          />
                          {errors.otp && (
                            <div className="invalid-feedback d-block">{errors.otp.message}</div>
                          )}
                          {otpSent && (
                            <ResendOTP
                              timer={timer}
                              onResend={handleResendOTP}
                              loading={sendOTPMutation.isPending}
                            />
                          )}
                        </div>

                        <div className="col-12">
                          {!otpSent ? (
                            <button
                              type="button"
                              className="buttons btnColor-first w-100 p-0"
                              disabled={sendOTPMutation.isPending || !isEmailValid || !smsConsent}
                              onClick={handleSendOTP}
                            >
                              {sendOTPMutation.isPending ? "Please wait..." : "Send OTP"}
                            </button>
                          ) : (
                            <button
                              type="submit"
                              className="buttons btnColor-first w-100 p-0"
                              disabled={
                                completeSignupMutation.isPending ||
                                sendOTPMutation.isPending ||
                                !smsConsent ||
                                !otp ||
                                otp.length !== 4
                              }
                            >
                              {completeSignupMutation.isPending
                                ? "Please wait..."
                                : sendOTPMutation.isPending
                                  ? "Sending OTP..."
                                  : "Register"}
                            </button>

                          )}

                        </div>
                      </div>
                    </form>

                    <div className="loginBar d-flex align-items-center gap-2">
                      <div className="line"></div>
                      <p className="text-line text-center text-xs mb-0">OR</p>
                      <div className="line"></div>
                    </div>

                    {socialError && (
                      <div className="alert alert-danger py-2 small mb-0" role="alert">
                        {socialError}
                      </div>
                    )}

                    <SocialAuthButtons onError={(msg) => setSocialError(msg)} onSuccess={onAuthSuccess} />

                    <p className="text-center text-sm">
                      Already have an account{" "}
                      <span onClick={goSignin} className="text-sm color-text-first fw-600 cursor-pointer">
                        Sign In
                      </span>
                    </p>

                    <p className="form-check  text-center text-sm">
                      <input
                        className="form-check-input"
                        type="checkbox"
                        id="smsConsentCheckbox"
                        checked={smsConsent}
                        onChange={(e) => setSmsConsent(e.target.checked)}
                      />
                      By proceeding, you agree to Leisure&apos;s{" "}
                      <Link href="/privacy" className="color-text-first fw-600">
                        Privacy Policy
                      </Link>
                      ,{" "}
                      <Link
                        href="/user-agreement"
                        target="_blank"
                        rel="noopener noreferrer"
                        onClick={() => onClose()}
                        className="color-text-first fw-600"
                      >
                        User Agreement
                      </Link>{" "}  
                      and{" "}
                      <Link href="/terms" target="_blank" rel="noopener noreferrer" className="color-text-first fw-600">
                        T&amp;Cs
                      </Link>
                    </p>
                  </div>
                </div>
                <button className="bg-white p-2 btn-close" onClick={onClose}></button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
