"use client";
import React, { useEffect, useState } from "react";
import "./style.css";
import PhoneInput, { CountryData } from "react-phone-input-2";
import "react-phone-input-2/lib/high-res.css";
import toast from "react-hot-toast";
import { setUserMobile } from "@/app/store/Slice/MobileNumber";
import { useAppDispatch } from "@/app/hooks/hooks";
import useApiPost from "@/app/hooks/postData";
import { setUserEmail } from "@/app/store/Slice/Email";
import { ClipLoader } from "react-spinners";
import TextTranslate from "@/app/utils/TextTranslate";
import { useTranslateText } from "@/app/hooks/useTranslate";
import { showSuccessToast } from "@/app/components/Toast/SuccessToast";
import { showErrorToast } from "@/app/components/Toast/ErrorToast";

function SigninForm({
  onSendOTP,
  selectedOption,
  setSelectedOption,
  demoValue,
}: {
  onSendOTP: () => void;
  selectedOption: "email" | "phone";
  setSelectedOption: React.Dispatch<React.SetStateAction<"email" | "phone">>;
  demoValue: { type: "email" | "phone"; value: string } | null;
}) {
  const { loading, data, error, postData } = useApiPost();
  const [inputValue, setInputValue] = useState("");
  const [phoneNumber, setPhoneNumber] = useState<string>("");
  const [countryName, setCountryName] = useState();
  const [selectedCountryDialCode, setSelectedCountryDialCode] =
    useState<string>("");

  const dispatch = useAppDispatch();
  const translate = useTranslateText();

  const handleInputChange = (
    value: string | React.ChangeEvent<HTMLInputElement>
  ) => {
    if (typeof value === "string") {
      setInputValue(value);
    } else {
      setInputValue(value.target.value);
    }
  };

  const [loading1, setLoading] = useState(false);
  const validateEmail = (email: string) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const handleSendOTP = async (
    e:
      | React.MouseEvent<HTMLButtonElement>
      | React.KeyboardEvent<HTMLInputElement>
  ) => {
    e.preventDefault();

    let payload: any = {};
    let apiEndpoint = "";

    if (selectedOption === "phone") {
      if (!phoneNumber || !selectedCountryDialCode) {
        showErrorToast("Please enter a valid phone number.");
        return;
      }

      const dialCode = selectedCountryDialCode.replace("+", "");
      const mobile = phoneNumber.replace(dialCode, "").replace(/\D/g, "");

      if (mobile.length < 5) {
        showErrorToast("Invalid phone number format.");
        return;
      }

      payload = {
        mobile,
        country_code: selectedCountryDialCode,
        platform_type: "Website",
        country: countryName,
      };

      dispatch(setUserMobile({ mobile, country_code: selectedCountryDialCode }));
      apiEndpoint = "/send_otp";
    }

    if (selectedOption === "email") {
      if (!inputValue) {
        showErrorToast("Please enter your email.");
        return;
      }

      if (!validateEmail(inputValue)) {
        showErrorToast("Invalid email format. Please enter a valid email.");
        return;
      }

      payload = {
        email: inputValue,
        platform_type: "Website",
        country: countryName,
      };

      dispatch(setUserEmail({ email: inputValue }));
      apiEndpoint = "/email_send_otp";
    }

    setLoading(true);
    try {
      const response = await postData(apiEndpoint, payload);
      showSuccessToast(response?.message || "OTP sent successfully!" , "Please check your inbox.");
      onSendOTP();
    } catch (error: any) {
      showErrorToast(error?.data?.message || "Something went wrong.");
      console.error("OTP Sending Error:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (
      e.key === "Enter" &&
      ((selectedOption === "phone" && phoneNumber) ||
        (selectedOption === "email" && inputValue))
    ) {
      e.preventDefault();
      handleSendOTP(e);
    }
  };

  useEffect(() => {
    if (demoValue?.type === "phone" && selectedOption === "phone") {
      setPhoneNumber(demoValue.value);
    } else if (demoValue?.type === "email" && selectedOption === "email") {
      setInputValue(demoValue.value);
    }
  }, [demoValue, selectedOption]);

  return (
    <div className="w-full">
      <form className="w-full mt-4 flex flex-col gap-3">

        <div className="w-full flex flex-col items-center">
          {/* Title Section */}
          <h2 className='text-center font-gilroy_semibold text-[var(--text-primary)] text-base xl:text-lg font-bold pb-4'>
            <TextTranslate text="Welcome back" />
          </h2>

          {/* Pill Toggle Section with Animated Slider */}
          <div className="relative flex w-full max-w-[320px] p-1 bg-[#8963D7] bg-opacity-15 dark:bg-opacity-[0.18]  rounded-full overflow-hidden">

            {/* The Sliding Background Pill */}
            <div
              className={`absolute top-1 bottom-1 left-1 w-[calc(50%-4px)] bg-[#6C47B7]  rounded-full transition-transform duration-300 ease-in-out shadow-sm z-0 ${selectedOption === "phone" ? "translate-x-full" : "translate-x-0"
                }`}
            />

            <button
              className={`relative flex-1 py-2 px-4 rounded-full text-sm font-semibold transition-colors duration-300 z-10 ${selectedOption === "email" ? "text-white" : "text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
                }`}
              onClick={(e) => {
                e.preventDefault();
                setSelectedOption("email");
              }}
            >
              <TextTranslate text="Email" />
            </button>

            <button
              className={`relative flex-1 py-2 px-4 rounded-full text-sm font-semibold transition-colors duration-300 z-10 ${selectedOption === "phone" ? "text-white" : "text-[#6C47B7]/60 hover:text-[var(--text-primary)]"
                }`}
              onClick={(e) => {
                e.preventDefault();
                setSelectedOption("phone");
              }}
            >
              <TextTranslate text="Phone" />
            </button>
          </div>
        </div>



        {/* Input Container */}
        <div className="w-full">
          {selectedOption === "phone" ? (
            <div className="phone-input-container w-full">
              <PhoneInput
                placeholder={translate("Mobile number")}
                country="in"
                value={phoneNumber}
                onChange={(value, data: CountryData) => {
                  setPhoneNumber(value);
                  setCountryName(data.name as any);
                  setSelectedCountryDialCode(`+${data.dialCode}`);
                }}
                inputProps={{
                  autoComplete: "new-mobile",
                  autoCorrect: "off",
                  spellCheck: "false",
                }}
                containerStyle={{
                  width: "100%",
                  border: "1px solid var(--border-colordark)",
                  borderRadius: "10px",
                  backgroundColor: "var(--modal-color)",
                }}
                inputStyle={{
                  width: "100%",
                  height: "54px",
                  backgroundColor: "transparent",
                  color: "var(--text-primary)",
                  border: "none",
                  borderRadius: "10px",
                  fontSize: "16px",
                  paddingLeft: "65px",
                }}
                buttonStyle={{
                  backgroundColor: "transparent",
                  border: "none",
                  borderRadius: "10px 0 0 10px",
                  height: "52px",
                }}
                dropdownStyle={{
                  backgroundColor: "var(--bg-primary)",
                  color: "black",
                  borderRadius: "4px",
                  zIndex: 50,
                }}
                onKeyDown={handleKeyDown}
                enableSearch
              />
            </div>
          ) : (
            <div className="relative w-full">
              <input
                type="email"
                value={inputValue}
                onChange={handleInputChange}
                autoComplete="new-email"
                autoCorrect="off"
                spellCheck="false"
                placeholder={translate("Email address")}
                className="w-full h-[47px] px-3 py-3.5 text-[16px] rounded-[10px] bg-[var(--modal-color)] text-[var(--text-primary)] border border-[var(--border-colordark)] focus:border-gray-400 outline-none transition-all placeholder:text-[#828282]"
                onKeyDown={handleKeyDown}
              />
            </div>
          )}
        </div>

        {/* Validation Message */}
        {selectedOption === "email" && inputValue && !validateEmail(inputValue) && (
          <div className="flex items-center gap-2 -mt-1.5">
            <img src="/assets/NotValid.png" className="w-3.5 h-3.5" alt="invalid" />
            <p className="text-[12px] text-red-500">Not valid email format</p>
          </div>
        )}

        {/* Submit Button */}
        <div className="mt-2">
          <button
            className={`py-2.5 lg:py-3 rounded-full bg-[#341F60] hover:opacity-90 text-white font-semibold text-[15px] w-full transition-all duration-300 flex items-center justify-center ${(selectedOption === "phone" && phoneNumber) ||
              (selectedOption === "email" && inputValue)
              ? "opacity-100"
              : "opacity-100 cursor-not-allowed"
              }`}
            disabled={
              (!phoneNumber && selectedOption === "phone") ||
              (!inputValue && selectedOption === "email") ||
              loading
            }
            onClick={(e) => {
              e.preventDefault();
              handleSendOTP(e);
            }}
          >
            {loading ? (
              <ClipLoader color="#FFFFFF" size={22} loading={loading} />
            ) : (
              <TextTranslate text="Send OTP" />
            )}
          </button>
        </div>
      </form>
    </div>
  );
}

export default SigninForm;