import React, { useContext, useEffect } from "react";
import PropTypes from "prop-types";
import {
  UserCardContainer,
  Avatar,
  UserName,
  Handle,
  UserDetail,
} from "./styles";
import Loader from "../../loader";
import { OutletContext } from "../../AppMainLayout";
const UserCard = ({ isOpen, findText }) => {
  const { generalData, accountName, userDetails } = useContext(OutletContext);
  const selectedAccount = generalData?.selectedAccount;

  useEffect(() => {
    if (selectedAccount?.id && selectedAccount?.type) {
      const date = new Date();
      const domain = window.location.href.includes("localhost")
        ? "localhost"
        : window.location.hostname?.includes("ca")
          ? ".learngual.ca"
          : ".learngual.com";
      date.setDate(date.getDate() + 28);
      document.cookie =
        "activeDeveloperAccount=" +
        selectedAccount.id +
        `; path=/; domain=${domain}; expires=${date.toUTCString()};`;
      document.cookie =
        "defaultAccountID=" +
        selectedAccount.id +
        `; path=/; domain=${domain}; expires=${date.toUTCString()};`;
      document.cookie =
        "defaultAccountType=" +
        selectedAccount.type +
        `; path=/; domain=${domain}; expires=${date.toUTCString()};`;
    }
  }, [selectedAccount?.id, selectedAccount?.type]);

  return (
    <UserCardContainer isOpen={isOpen}>
      {userDetails?.loading && !accountName ? (
        <Loader zoom={0.3} isOpen={isOpen} />
      ) : (
        <>
          <Avatar
            src={selectedAccount?.profile_photo?.url}
            isOpen={isOpen}
            onClick={() => {
              if (selectedAccount?.type?.toLowerCase() !== "personal") {
                window.location.href = `/${selectedAccount?.type?.toLowerCase()}/profile`;
              }
            }}
          />
          <UserDetail
            isOpen={isOpen}
            onClick={() => {
              if (
                selectedAccount?.type?.toLowerCase() !== "personal" ||
                selectedAccount?.type?.toLowerCase() !== "developer"
              ) {
                window.location.href = `/${selectedAccount?.type?.toLowerCase()}/profile`;
              }
            }}
          >
            <UserName>{findText("Hello")}</UserName>
            <Handle
              style={{
                textTransform: "capitalize",
                fontWeight: 700,
                fontSize: 15,
              }}
            >
              {accountName?.length >= 25
                ? accountName?.slice(0, 25)?.trim() + "..."
                : accountName}
            </Handle>
          </UserDetail>
        </>
      )}
    </UserCardContainer>
  );
};
UserCard.propTypes = {
  user: PropTypes.shape({
    avatar: PropTypes.string.isRequired,
    name: PropTypes.string.isRequired,
    handle: PropTypes.string.isRequired,
  }).isRequired,
  isOpen: PropTypes.bool.isRequired,
};
export default UserCard;
