import React, { useEffect, useState } from "react";
import { LogoutIcon, ProfileImgPIB } from "./MyProfile.styled";
import HeaderPopover from "../HeaderPopover/HeaderPopover";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector } from "react-redux";
import { selectMineProfile } from "../../../store/selectors/profileSelectors";
import { selectUserId } from "../../../store/selectors/loginSelectors";
import { fetchMineProfile } from "../../../store/actions/profile/profileActions";
import selectedTheme from "../../../themes";
import { EyeIcon } from "../HeaderPopover/HeaderPopover.styled";
import { logoutUser } from "../../../store/actions/login/loginActions";
import { useHistory } from "react-router-dom";
import { LOGIN_PAGE } from "../../../constants/pages";

export const MyProfile = () => {
  const { t } = useTranslation();
  const profile = useSelector(selectMineProfile);
  const userId = useSelector(selectUserId);
  const dispatch = useDispatch();
  const history = useHistory();
  const [profileAsArray, setProfileAsArray] = useState([]);
  useEffect(() => {
    if (userId?.length > 1) {
      dispatch(fetchMineProfile());
    }
  }, [userId]);
  useEffect(() => {
    if (profile?.statistics) {
      setProfileAsArray([
        {
          src: profile.image,
          title: profile.company.name,
          onClick: () => seeMyProfile(),
          text: (
            <React.Fragment>
              <ProfileImgPIB />
              {`${t("itemDetailsCard.PIB")}${profile.company.PIB}`}
            </React.Fragment>
          ),
        },
      ]);
    }
  }, [profile]);
  const handleLogoutSuccess = () => {
    history.replace(LOGIN_PAGE);
  };
  const handleLogout = () => {
    dispatch(logoutUser(handleLogoutSuccess));
  };
  const seeMyProfile = () => {
    history.push(`/profile/${userId}`);
  }
  return (
    <HeaderPopover
      title={t("header.myProfile")}
      items={profileAsArray}
      buttonText={t("header.checkProfile")}
      buttonIcon={<EyeIcon color={selectedTheme.iconYellowColor} />}
      isProfile
      buttonOnClick={() => seeMyProfile()}
      secondButtonIcon={<LogoutIcon color={selectedTheme.iconYellowColor} />}
      secondButtonText={t("header.logout")}
      secondButtonOnClick={handleLogout}
    />
  );
};
