import React, { useEffect, useState, useContext } from "react";
import { AddIcon } from "./assets/svg/add";
import {
  AccountDropdownLayout,
  AccountDropdownHeader,
  AccountDropdownBody,
  AccountDropdownFooter,
} from "./index.styled";
import { FullPageLoader, OutletContext } from "..";
import deleteCookies from "../instructorAccountSwitcher/deleteCookies";
/**
 * @param {{
 *  type: string,
 *  text: string,
 *  onClick: Function,
 *  style: CSSProperties,
 * }} props - properties of Header Component
 *
 */
const AccountDropdown = (props) => {
  const { findAccountNames } = useContext(OutletContext);
  useEffect(() => {
    if (props?.selectedAccount) {
      console.log("selectedAccount", props?.selectedAccount);

      props?.setGeneralData((generalData) => ({
        ...generalData,
        accounts: props?.userAccountsDetail?.data,
        user: props?.userDetails?.data,
        selectedAccount: props?.selectedAccount,
      }));
    }
  }, [props?.selectedAccount]);

  const handleRedirectFunc = ({ type }) => {
    // optimize the use of this base later because it's redeclared on multiple files
    const base = `${
      window.location.hostname.includes("localhost") ||
      window.location.hostname.includes("staging")
        ? `https://559staging.learngual.${
            window.location.hostname.includes(".ca") ? "ca" : "com"
          }`
        : `https://www.learngual.${
            window.location.hostname.includes(".ca") ? "ca" : "com"
          }`
    }`;
    if (window.location.port) {
      window.location.href = `${window.location.protocol}//${
        window.location.hostname
      }:${window.location.port}/${type?.toLowerCase()}`;
    } else {
      window.location.href = `${base}/${type?.toLowerCase()}`;
    }
  };

  const [isLoading, setIsLoading] = useState(false);

  const clearSwitchCookies = () => {
    [
      "defaultAccountType",
      "defaultAccountID",
      "activeDeveloperAccount",
    ].forEach((cookieName) => {
      deleteCookies(cookieName);
    });
  };

  const handleAccountSwitch = async (nextAccount) => {
    const nextAccountId = nextAccount?.id;

    if (!nextAccountId || isLoading) return;
    if (nextAccountId === props?.selectedAccount?.id) return;

    const previousAccount = props?.selectedAccount;

    try {
      setIsLoading(true);

      const response = await props?.handleSetDefaultAccount(nextAccountId);
      const statusCode = response?.status || response?.response?.status;
      const isSuccess = String(statusCode).startsWith("2");

      if (!isSuccess) {
        props?.setSelectedAccount(previousAccount);
        setIsLoading(false);
        return;
      }

      clearSwitchCookies();
      props?.setSelectedAccount(nextAccount);
      handleRedirectFunc(nextAccount);
    } catch (error) {
      props?.setSelectedAccount(previousAccount);
      setIsLoading(false);
    }
  };

  return (
    <>
      <AccountDropdownLayout ref={props?.ref}>
        <AccountDropdownHeader>
          <div className="img_div">
            <img
              src={props?.selectedAccount?.profile_photo?.url || props?.avatar}
              alt={props?.findText("account photo")}
            />
          </div>
          <div>
            <h1
              style={{
                textTransform: "capitalize",
              }}
            >
              {" "}
              {findAccountNames(props?.selectedAccount)}
            </h1>
            <h2
              style={{
                textTransform: "capitalize",
              }}
            >
              {props?.selectedAccount?.type?.toLowerCase() === "personal"
                ? props?.findText("Student")
                : props
                    ?.findText(props?.selectedAccount?.type?.toUpperCase())
                    ?.toLowerCase() ||
                  props?.findText(props.activeAccountType)}{" "}
            </h2>
          </div>
        </AccountDropdownHeader>
        <AccountDropdownBody>
          <>
            {props?.developerAccountData.length > 0 && (
              <div>
                <h3
                  style={{
                    marginBottom: 10,
                  }}
                >
                  {props.findText("Developer accounts")}
                </h3>
                {props?.developerAccountData?.map((developerItem, idx) => {
                  return (
                    <div
                      className={`account-info ${
                        developerItem?.id === props?.selectedAccount?.id
                          ? "activated"
                          : ""
                      }`}
                      onClick={() => {
                        handleAccountSwitch(developerItem);
                      }}
                      key={idx}
                    >
                      <div className="avatar-container">
                        <img
                          src={
                            developerItem?.profile_photo?.url || props.avatar
                          }
                          alt={props?.findText("account photo")}
                        />
                      </div>
                      <div className="account-details">
                        <h1
                          style={{
                            textTransform: "capitalize",
                          }}
                        >
                          {" "}
                          {findAccountNames(developerItem) || props.accountName}
                        </h1>
                        {developerItem?.notification_count > 0 && (
                          <span>{developerItem?.notification_count}</span>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </>

          <>
            {props?.instructorAccountData?.length > 0 && (
              <div>
                <h3
                  style={{
                    marginBottom: 10,
                  }}
                >
                  {props.findText("Instructor account")}
                </h3>
                {props?.instructorAccountData?.map((instructorItem, idx) => {
                  return (
                    <div
                      className={`account-info ${
                        instructorItem?.id === props?.selectedAccount?.id
                          ? "activated"
                          : ""
                      }`}
                      onClick={() => {
                        handleAccountSwitch(instructorItem);
                      }}
                      key={idx}
                    >
                      <div className="avatar-container">
                        <img
                          src={
                            instructorItem?.profile_photo?.url || props.avatar
                          }
                          alt={props?.findText("account photo")}
                        />
                      </div>
                      <div className="account-details">
                        <h1>
                          {" "}
                          {findAccountNames(instructorItem) ||
                            props.accountName}
                        </h1>
                        {instructorItem?.notification_count > 0 && (
                          <span>{instructorItem?.notification_count} </span>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
            {props?.enterpriseAccountData?.length > 0 && (
              <div>
                <h3
                  style={{
                    marginBottom: 10,
                  }}
                >
                  {props?.findText("Enterprise account")}
                </h3>
                {props?.enterpriseAccountData?.map((enterpriseItem, idx) => (
                  <div
                    className={`account-info ${
                      enterpriseItem?.id === props?.selectedAccount?.id
                        ? "activated"
                        : ""
                    }`}
                    onClick={() => {
                      handleAccountSwitch(enterpriseItem);
                    }}
                    key={idx}
                  >
                    <div className="avatar-container">
                      <img
                        src={enterpriseItem?.profile_photo?.url || props.avatar}
                        alt={props?.findText("account photo")}
                      />
                    </div>
                    <div className="account-details">
                      <h1>
                        {" "}
                        {findAccountNames(enterpriseItem) || props.accountName}
                      </h1>
                      {enterpriseItem?.notification_count > 0 && (
                        <span>{enterpriseItem?.notification_count} </span>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}

            {
              // dont show personal accounts for developer user
              props?.personalAccountData?.length > 0 && (
                <div>
                  <h3
                    style={{
                      marginBottom: 10,
                    }}
                  >
                    {props?.findText("Student account")}
                  </h3>
                  {props?.personalAccountData?.map((personalItem, idx) => (
                    <div
                      className={`account-info ${
                        personalItem?.id === props?.selectedAccount?.id
                          ? "activated"
                          : ""
                      }`}
                      onClick={() => {
                        handleAccountSwitch(personalItem);
                      }}
                      key={idx}
                    >
                      <div className="avatar-container">
                        <img
                          src={personalItem?.profile_photo?.url || props.avatar}
                          alt={props?.findText("account photo")}
                        />
                      </div>
                      <div className="account-details">
                        <h1>
                          {" "}
                          {findAccountNames(personalItem) || props.accountName}
                        </h1>
                        {personalItem?.notification_count > 0 && (
                          <span>{personalItem?.notification_count} </span>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              )
            }
          </>
        </AccountDropdownBody>

        <AccountDropdownFooter>
          <button
            onClick={() => {
              window.location.hostname?.includes("coming")
                ? (window.location.href =
                    "https://learngual.com/auth/account-type")
                : (window.location.href = "/auth/account-type");
            }}
            style={{
              cursor: "pointer",
            }}
          >
            <AddIcon /> {props.findText("Add account")}
          </button>
        </AccountDropdownFooter>
      </AccountDropdownLayout>
      {isLoading && <FullPageLoader hasBackground fixed={true} />}
    </>
  );
};
export default AccountDropdown;
