// eslint-disable-next-line import/no-unresolved
import { parseInput } from "@leekone/bnsjs/utils/validation";
import { LOGIN_PROVIDER, OPENLOGIN_NETWORK_TYPE } from "@toruslabs/openlogin-utils";
import { ChangeEvent, FormEvent, useContext, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";

import { ThemedContext } from "../context/ThemeContext";
import { getUserCountry, validatePhoneNumber } from "../utils";
import { BNSContext } from "./BNSProvider";
import Icon from "./Icon";

interface SocialLoginPasswordlessProps {
  isPrimaryBtn: boolean;
  isEmailVisible: boolean;
  isSmsVisible: boolean;
  adapter: string;
  web3AuthNetwork: OPENLOGIN_NETWORK_TYPE;
  handleSocialLoginClick: (params: { adapter: string; loginParams: { loginProvider: string; login_hint?: string; name: string } }) => void;
}
enum BiuStatus {
  Available = "Available",
  Unavailable = "Unavailable",
  TooShort = "TooShort",
  Registered = "registered",
  Loading = "Loading",
  UnOpen = "unOpen",
  Appointment = "Appointment",
}
export default function SocialLoginPasswordless(props: SocialLoginPasswordlessProps) {
  const { handleSocialLoginClick, adapter, web3AuthNetwork, isPrimaryBtn, isEmailVisible, isSmsVisible } = props;
  const { isDark } = useContext(ThemedContext);

  const [fieldValue, setFieldValue] = useState<string>("");
  const [countryCode, setCountryCode] = useState<string>("");
  const [isValidInput, setIsValidInput] = useState<boolean | null>(null);
  const [biuValue, setBiuValue] = useState<string>("");
  const [biuStatus, setBiuStatus] = useState<BiuStatus>(BiuStatus.Available);
  const [loading, setLoading] = useState<boolean>(false);
  const bns = BNSContext();
  const [t] = useTranslation();
  const inputRef = useRef(null);
  const handleFormSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const value = fieldValue;
    const isEmailValid = value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i);
    if (isEmailValid) {
      return handleSocialLoginClick({ adapter, loginParams: { loginProvider: LOGIN_PROVIDER.EMAIL_PASSWORDLESS, login_hint: value, name: "Email" } });
    }
    const number = value.startsWith("+") ? value : `${countryCode}${value}`;
    const result = await validatePhoneNumber(number, web3AuthNetwork);
    if (result) {
      return handleSocialLoginClick({
        adapter,
        loginParams: { loginProvider: LOGIN_PROVIDER.SMS_PASSWORDLESS, login_hint: typeof result === "string" ? result : number, name: "Mobile" },
      });
    }

    setIsValidInput(false);
    return undefined;
  };

  useEffect(() => {
    const getLocation = async () => {
      const result = await getUserCountry(web3AuthNetwork);
      if (result && result.dialCode) {
        setCountryCode(result.dialCode);
      }
    };
    if (isSmsVisible) getLocation();
  }, [isSmsVisible, web3AuthNetwork]);

  const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    setFieldValue(e.target.value);
    if (isValidInput === false) setIsValidInput(null);
  };
  const getAppointment = async (name: string) => {
    const res = await fetch("https://biubiu.id/ens/has_appointment", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        ens: name,
        operationID: `${Date.now()}`,
      }),
    });
    if (res) {
      const status = await res.json();
      return status.data;
    }
    return false;
  };
  const failedTip = useMemo(() => {
    switch (biuStatus) {
      case BiuStatus.Available:
        return t("modal.ens.Available");
      case BiuStatus.UnOpen:
        return t("modal.ens.Notyetopen");
      case BiuStatus.Unavailable:
        return t("modal.ens.InvalidFormatforName");
      case BiuStatus.TooShort:
        return t("modal.ens.TooShort");
      case BiuStatus.Loading:
        return t("modal.ens.Inquiring");
      case BiuStatus.Registered:
        return t("modal.ens.Registered");
      case BiuStatus.Appointment:
        return t("modal.ens.appointed");
      default:
        return t("modal.ens.Inquiring");
    }
  }, [biuValue, biuStatus]);

  // eslint-disable-next-line consistent-return
  const handleInputBiuChange = (e: ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.trim().toLowerCase();
    setLoading(true);
    setBiuValue(value);
    if (value.length < 3) {
      setBiuStatus(BiuStatus.TooShort);
      return false;
    }
    Promise.all([bns.getValid(`${value}.biu`), bns.getAvailable(`${value.trim()}.biu`), getAppointment(`${value}.biu`)])
      .then(([valid, available, appointed]) => {
        setLoading(false);
        if (!parseInput(`${value}.biu`).isValid) {
          setBiuStatus(BiuStatus.Unavailable);
          return false;
        }
        if (!valid) {
          setBiuStatus(BiuStatus.UnOpen);
          return false;
        }
        if (appointed) {
          setBiuStatus(BiuStatus.Appointment);
          return false;
        }
        if (available && valid) {
          localStorage.setItem("temporaryName", value);
          setBiuStatus(BiuStatus.Available);
          return false;
        }
        if (valid && !available) {
          setBiuStatus(BiuStatus.Registered);
          return false;
        }
        setBiuStatus(BiuStatus.Available);
        localStorage.setItem("temporaryName", value);
        return true;
      })
      .catch(() => {
        setLoading(false);
        setBiuStatus(BiuStatus.Unavailable);
        return false;
      });
  };
  useEffect(() => {
    const temporaryName = localStorage.getItem("temporaryName");
    if (temporaryName && inputRef.current) {
      inputRef.current.value = temporaryName;
      handleInputBiuChange({ target: { value: inputRef.current.value } } as any);
    }
  }, [inputRef]);
  const placeholder = useMemo(() => {
    if (isEmailVisible && isSmsVisible) return "+(00)123456/name@example.com";
    if (isEmailVisible) return "name@example.com";
    return "+(00)123456";
  }, [isEmailVisible, isSmsVisible]);

  return (
    <div className="w3ajs-passwordless w3a-group w3a-group--passwordless">
      <div className="w3a-group__title">
        {isSmsVisible && (
          <div className="relative flex flex-col items-center cursor-pointer group">
            <Icon iconName={`information-circle${isDark ? "-light" : ""}`} />
            <div className="absolute z-20 flex-col items-center hidden mb-5 top-4 group-hover:flex">
              <div className="w-3 h-3 ml-[3px] -mb-2 rotate-45 bg-app-gray-50 dark:bg-app-gray-600" />
              <div className="relative p-4 w-[200px] text-xs leading-none text-white rounded-md bg-app-gray-50 dark:bg-app-gray-600 shadow-lg">
                <div className="mb-1 text-xs font-medium text-app-gray-900 dark:text-white">{t("modal.popup.phone-header")}</div>
                <div className="text-xs text-app-gray-400">{t("modal.popup.phone-body")}</div>
              </div>
            </div>
          </div>
        )}
      </div>
      <form className="w3ajs-passwordless-form" onSubmit={(e) => handleFormSubmit(e)}>
        <div className="w3a-biu-wrap">
          <span className="w3a-biubiu-prefix">biubiu.id/</span>
          <input
            ref={inputRef}
            autoComplete="off"
            className="w-full w3a-text-field pd106"
            name="bns"
            placeholder=".biu"
            onBlur={(e) => handleInputBiuChange(e)}
          />
          {!loading && biuValue && biuStatus !== BiuStatus.Available && (
            <div style={{ marginTop: "-10px", marginBottom: "10px" }} className="w3a-sms-field--error">
              {failedTip}
            </div>
          )}
          <span className="w3a-input-status">
            {loading && biuValue && (
              <div style={{ width: "14px", height: "14px", position: "absolute" }} className="w3ajs-modal-loader__spinner w3a-spinner">
                <div style={{ width: "0", height: 0 }} className="w3a-spinner__head" />
                <div style={{ width: "4px", height: "4px" }} className="w3a-spinner__mask" />
              </div>
            )}
            {!loading && biuValue && biuStatus === BiuStatus.Available && <Icon iconName="success" />}
            {!loading && biuValue && biuStatus !== BiuStatus.Available && <Icon iconName="failed" />}
          </span>
        </div>

        <input
          className="w-full mb-4 w3a-text-field"
          autoComplete="off"
          name="passwordless-input"
          required
          placeholder={`${t("modal.social.sms-placeholder-text")} ${placeholder}`}
          onFocus={(e) => (e.target.placeholder = "")}
          onBlur={(e) => (e.target.placeholder = `${t("modal.social.sms-placeholder-text")} ${placeholder}`)}
          onChange={(e) => handleInputChange(e)}
        />

        {isValidInput === false && <div className="w3a-sms-field--error">{t("modal.errors-invalid-number-email")}</div>}

        <button
          style={{ marginTop: "26px" }}
          disabled={fieldValue === ""}
          className={`w3a-button ${isPrimaryBtn ? "w3a-button--primary" : ""} w-full`}
          type="submit"
        >
          {t("modal.social.passwordless-cta")}
        </button>
      </form>
    </div>
  );
}
