import "react-phone-input-2/lib/high-res.css";
import PhoneInputField from "./PhoneInputField";
import { useNavigate } from "react-router-dom";
import useApiPost from "../../hooks/PostData";

import { ClipLoader } from "react-spinners";
import LoginLeftSections from "./LoginLeftSections";
import toast from "react-hot-toast";
import { useWebsiteSettings } from "../../store/api/useWebsiteSettings";
import { TbCopy } from "react-icons/tb";
import EmailInputField from "./EmailInputField";
import { useEffect, useState } from "react";
import { useTheme } from "../../context/ThemeProvider";

export default function Login() {
  const navigate = useNavigate();
  const { loading, postData } = useApiPost();
  const { data: websiteSettings } = useWebsiteSettings();

  const [formData, setFormData] = useState({
    country_code: "",
    mobile_num: "",
    country: "",
    country_full_name: "",
    email_id: "",
  });

  const { theme } = useTheme();
  const [currentLoginField, setCurrentLoginField] = useState<"email" | "phone">(
    "phone",
  );
  const [bothLoginEnabled, setBothLoginEnabled] = useState(false);
  useEffect(() => {
    if (
      websiteSettings?.data.email_authentication &&
      websiteSettings?.data.phone_authentication
    ) {
      setBothLoginEnabled(true);
    } else if (websiteSettings?.data.phone_authentication) {
      setCurrentLoginField("phone");
      setBothLoginEnabled(false);
    } else if (websiteSettings?.data.email_authentication) {
      setCurrentLoginField("email");
    }
  }, [websiteSettings?.data]);

  async function postPhoneNumber() {
    if (formData.mobile_num == "" || formData.mobile_num == undefined) {
      toast.error("Please Enter Phone Number", { position: "bottom-center" });
      return;
    }
    sessionStorage.setItem("country", formData.country.toUpperCase());
    sessionStorage.setItem("country_full_name", formData.country_full_name);
    try {
      // Remove country code from phone number
      const mobile_num = formData.mobile_num.replace(formData.country_code, "");

      if (mobile_num == "" || mobile_num == undefined) {
        toast.error("Please Enter Phone Number", { position: "bottom-center" });
        return;
      }

      const dataToSend = {
        country_code: formData.country_code,
        mobile_num: mobile_num,
        country_short_name: formData.country,
        country: formData.country_full_name,
        login_type: "phone",
        platform: "web",
      };

      // console.log(dataToSend, "dataToSend");
      const registerPhoneRes = await postData("users/signup", dataToSend);
      // console.log(registerPhoneRes.success == true);
      if (registerPhoneRes.status == true) {
        sessionStorage.setItem("dataToSend", JSON.stringify(dataToSend));
        navigate("/otp-verification");
      } else {
        toast.error(registerPhoneRes.message);
        return;
        // toast.error(registerPhoneRes.message);
      }
    } catch (error) {
      if ((error as Error).status == 429) {
        toast.error("You have already exceed the login limit!");
      } else {
        toast.error(error.message);
      }

      console.log(error);
    }

    // addUserPhone(formData.phone);
  }

  async function postEmailId() {
    if (formData.email_id == "" || formData.email_id == undefined) {
      toast.error("Please Enter Email Number", { position: "bottom-center" });
      return;
    }
    const dataToSend = {
      ...formData,
      email_id: formData.email_id,
    };

    try {
      // console.log(dataToSend, "dataToSend");
      let registerEmailRes = await postData("users/signup", {
        email_id: formData.email_id,
      });
      // console.log(registerEmailRes.success == true);
      if (registerEmailRes.success == true) {
        sessionStorage.setItem("dataToSend", JSON.stringify(dataToSend));
        navigate("/otp-verification");
      } else {
        toast.error(registerEmailRes.message);
        return;
        // toast.error(registerPhoneRes.message);
      }
    } catch (error) {
      toast.error((error as Error).message);
    }

    // addUserPhone(formData.phone);
  }
  return (
    <div className="grid min-h-screen w-screen bg-white text-black lg:grid-cols-2">
      {/* Sign in Left side ====================================================================================*/}
      <LoginLeftSections />

      {/* Sign in Right side ====================================================================================*/}
      <div
        className="relative col-span-1 flex h-full w-full flex-col items-center justify-center bg-cover bg-center"
        style={{
          backgroundImage: `url(${"/Home/Login_page.jpg"})`,
        }}
      >
        <img
          className="absolute right-5 top-5 w-20 xl:w-28"
          src={theme === "dark" ? websiteSettings?.data.web_logo_dark : websiteSettings?.data.web_logo_light}
          alt=""
        />
        <div className="mx-auto w-[90%] max-w-[30rem] space-y-7 rounded-2xl p-5 shadow-[rgba(17,_17,_26,_0.1)_0px_0px_16px] lg:p-10 2xl:max-w-[35rem] 2xl:p-16">
          {/* <div className="flex">
            <h4 className="mr-3 text-3xl font-medium">Welcome</h4>
            <img className="h-8 w-8" src="/LightIcons/hii.png" alt="" />
          </div> */}
          <div className="text-lg lg:text-2xl">
            Hello welcome to {websiteSettings?.data.app_name}
          </div>
          <div>
            {bothLoginEnabled && (
              <div className="grid grid-cols-2 text-center">
                <div
                  onClick={() => {
                    setCurrentLoginField("phone");
                  }}
                  className={`flex h-12 cursor-pointer items-center justify-center gap-2 ${currentLoginField == "phone" ? "primary-gradient" : "border"} rounded-t-lg py-3`}
                >
                  <span className="hidden lg:block"> Continue with </span>{" "}
                  <span>Phone</span>
                </div>
                <div
                  onClick={() => {
                    setCurrentLoginField("email");
                  }}
                  className={`flex h-12 cursor-pointer items-center justify-center gap-2 ${currentLoginField == "email" ? "primary-gradient" : "border"} rounded-t-lg py-3`}
                >
                  <span className="hidden lg:block"> Continue with</span>{" "}
                  <span>Email</span>
                </div>
              </div>
            )}

            <div>
              {currentLoginField == "phone" ? (
                <PhoneInputField
                  postPhoneNumber={postPhoneNumber}
                  formData={formData}
                  setFormData={setFormData}
                  bothLoginEnabled={bothLoginEnabled}
                />
              ) : (
                <EmailInputField
                  postEmailId={postEmailId}
                  formData={formData}
                  setFormData={setFormData}
                  bothLoginEnabled={bothLoginEnabled}
                />
              )}
            </div>
          </div>

          <button
            onClick={() => {
              // clear session storage and local storage
              sessionStorage.clear();
              localStorage.clear();
              if (currentLoginField == "email") {
                postEmailId();
              } else {
                postPhoneNumber();
              }
            }}
            className={`primary-gradient relative h-12 w-full overflow-hidden rounded-lg px-4 py-2 text-base font-medium outline-none lg:px-9 lg:text-lg`}
          >
            {loading ? (
              <div className="px-5">
                <ClipLoader color="black" size={23} />
              </div>
            ) : (
              <span className="">{"Send OTP"}</span>
            )}
          </button>
        </div>
        {import.meta.env.VITE_IS_DEMO == "true" && (
          <div className="mx-auto mt-5 w-[90%] max-w-[30rem] rounded-xl bg-[#FFEDAB] p-4 2xl:max-w-[35rem]">
            <div className="font-semibold">For Demo</div>
            <hr className="my-3 border-t border-[#D8D8D8]" />
            <div className="flex justify-between">
              {currentLoginField == "phone" ? (
                <div className="flex w-full justify-between">
                  <div>
                    <span>Mobile Number : </span>
                    <span>+1 5628532467</span>
                  </div>
                  <div
                    onClick={() => {
                      setFormData((prevData) => ({
                        ...prevData, // Keep existing formData properties
                        country_code: `+${"1"}`,
                        mobile_num: `+${"15628532467"}`,
                      }));
                    }}
                    className="cursor-pointer"
                  >
                    <TbCopy className="text-xl" />
                  </div>
                </div>
              ) : (
                <>
                  <div className="flex w-full justify-between">
                    <div>
                      <span>Email Id : </span>
                      <span>whoxa@demo.com</span>
                    </div>
                    <div
                      onClick={() => {
                        setFormData((prevData) => ({
                          ...prevData, // Keep existing formData properties
                          email_id: "whoxa@demo.com",
                        }));
                      }}
                      className="cursor-pointer"
                    >
                      <TbCopy className="text-xl" />
                    </div>
                  </div>
                </>
              )}
            </div>
            <div>
              <span>Otp : </span>
              <span>123456</span>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
