import React from "react";
import PropTypes from "prop-types";
import {
  DownArrow,
  HeaderSelect,
  HeaderTitle,
  IconContainer,
  OffersContainer,
  OffersIcon,
  OffersScroller,
  ProfileOffersContainer,
  SearchIcon,
  SearchInput,
  SelectOption,
} from "./ProfileOffers.styled";
import { Grid } from "@mui/material";
import { useState } from "react";
import { sortEnum } from "../../../enums/sortEnum";
import { useEffect } from "react";
import { useSelector } from "react-redux";
import OfferCard from "../../Cards/OfferCard/OfferCard";
import { useTranslation } from "react-i18next";
import { useRef } from "react";
import { selectProfileOffers } from "../../../store/selectors/offersSelectors";
import useScreenDimensions from "../../../hooks/useScreenDimensions";
import { selectLatestChats } from "../../../store/selectors/chatSelectors";
import { useHistory } from "react-router-dom";
import { selectUserId } from "../../../store/selectors/loginSelectors";

const ProfileOffers = (props) => {
  const [sortOption, setSortOption] = useState(sortEnum.INITIAL);
  const [offersToShow, setOffersToShow] = useState([]);
  const searchRef = useRef(null);
  const chats = useSelector(selectLatestChats);
  const profileOffers = useSelector(selectProfileOffers);
  const dimensions = useScreenDimensions();
  const history = useHistory();
  const { t } = useTranslation();
  const userId = useSelector(selectUserId);

  const messageUser = (offer) => {
    const chatItem = chats.find(
      (item) => item.chat.offerId === offer?.offer?._id
    );
    if (chatItem !== undefined) {
      history.push(`/messages/${chatItem.chat._id}`);
    } else {
      if (offer?.offer?.userId !== userId) {
        history.push(`/messages/newMessage`, {
          offerId: offer?.offer?._id,
        });
      }
    }
  };

  useEffect(() => {
    let newOffersToShow = [...offersToShow];
    if (sortOption.value === sortEnum.OLD.value) {
      newOffersToShow.sort(
        (a, b) => new Date(a._created) - new Date(b._created)
      );
    }
    if (sortOption.value === sortEnum.NEW.value) {
      newOffersToShow.sort(
        (a, b) => new Date(b._created) - new Date(a._created)
      );
    }
    if (sortOption.value === sortEnum.POPULAR.value) {
      newOffersToShow.sort(
        (a, b) => a.views.viewers.length - b.views.viewers.length
      );
    }
    setOffersToShow([...newOffersToShow]);
  }, [sortOption]);

  useEffect(() => {
    if (profileOffers?.length > 0) setOffersToShow(profileOffers);
  }, [profileOffers]);

  const handleSearch = () => {
    const valueToSearch = searchRef?.current?.value;
    let newOffersToShow = profileOffers.filter((item) =>
      item.name.toLowerCase().includes(valueToSearch.toLowerCase())
    );
    setOffersToShow([...newOffersToShow]);
  };

  const handleChangeSelect = (event) => {
    let chosenOption;
    for (const sortOption in sortEnum) {
      if (sortEnum[sortOption].value === event.target.value) {
        chosenOption = sortEnum[sortOption];
        setSortOption(chosenOption);
      }
    }
  };

  let listener;
  const handleFocusSearch = () => {
    listener = (event) => {
      if (event.keyCode === 13) {
        event.preventDefault();
        handleSearch();
      }
    };
    searchRef.current.addEventListener("keyup", listener);
  };

  const handleBlurSearch = () => {
    searchRef.current.removeEventListener("keyup", listener);
  };

  return (
    <ProfileOffersContainer>
      <HeaderSelect
        value={sortOption?.value ? sortOption.value : sortEnum.INITIAL.value}
        IconComponent={DownArrow}
        onChange={handleChangeSelect}
      >
        {Object.keys(sortEnum).map((property) => {
          return (
            <SelectOption
              value={sortEnum[property].value}
              key={sortEnum[property].value}
            >
              {sortEnum[property].mainText}
            </SelectOption>
          );
        })}
      </HeaderSelect>
      <Grid
        container
        direction="row"
        justifyContent="start"
        alignItems="center"
        sx={{ mb: 1.4 }}
      >
        <OffersIcon />
        <HeaderTitle>
          {props.isMyProfile ? "Moje objave" : "Objave kompanije"}
        </HeaderTitle>
      </Grid>
      <SearchInput
        fullWidth
        ref={searchRef}
        onFocus={handleFocusSearch}
        onBlur={handleBlurSearch}
        // ref={searchRef}
        placeholder={t("header.searchOffers")}
        italicPlaceholder
        InputProps={{
          endAdornment: (
            <IconContainer onClick={handleSearch}>
              <SearchIcon />
            </IconContainer>
          ),
        }}
      />
      <OffersContainer>
        {dimensions.width > 600 ? (
          offersToShow.map((item) => (
            <OfferCard
              isMyOffer={props.isMyProfile}
              offer={item}
              key={JSON.stringify(item)}
              pinned
              messageUser={messageUser}
            />
          ))
        ) : (
          <OffersScroller hideArrows>
            {offersToShow.map((item) => (
              <OfferCard
                vertical
                isMyOffer={props.isMyProfile}
                offer={item}
                key={JSON.stringify(item)}
                pinned
                messageUser={messageUser}
              />
            ))}
          </OffersScroller>
        )}
      </OffersContainer>
    </ProfileOffersContainer>
  );
};

ProfileOffers.propTypes = {
  children: PropTypes.node,
  isMyProfile: PropTypes.bool,
};

export default ProfileOffers;
