import React, { useState, useEffect } from "react";
import ChatCard from "../Cards/ChatCard/ChatCard";
import {
  ChatColumnContainer,
  HeaderBack,
  HeaderSelect,
  ListContainer,
  ListHeader,
  SelectOption,
  TitleSortContainer,
} from "./ChatColumn.styled";
import { sortEnum } from "../../enums/sortEnum";
import { ReactComponent as Down } from "../../assets/images/svg/down-arrow.svg";
import { IconStyled } from "../Icon/Icon.styled";
import { Grid } from "@mui/material";
import MailOutlineIcon from "@mui/icons-material/MailOutline";
import { HeaderTitle } from "../ProfileCard/ProfileCard.styled";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector } from "react-redux";
import { selectLatestChats } from "../../store/selectors/chatSelectors";
import { fetchChats } from "../../store/actions/chat/chatActions";
import useSorting from "../../hooks/useOffers/useSorting";

export const DownArrow = (props) => {
  <IconStyled {...props}>
    <Down />
  </IconStyled>;
};

export const ChatColumn = () => {
  const dispatch = useDispatch();
  const sorting = useSorting();
  const { t } = useTranslation();
  const [sortOption, setSortOption] = useState(sortEnum.INITIAL);
  const chats = useSelector(selectLatestChats);

  useEffect(() => {
    dispatch(fetchChats());
  }, []);

  useEffect(() => {
    setSortOption(sorting.selectedSortOption);
  }, [sorting.selectedSortOption]);

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

  return (
    <ChatColumnContainer>
      <HeaderBack />
      <TitleSortContainer>
        <Grid
          container
          direction="row"
          justifyContent="start"
          alignItems="center"
        >
          <MailOutlineIcon color="action" sx={{ mr: 0.9 }} />
          <HeaderTitle>{t("header.myMessages")}</HeaderTitle>
        </Grid>
        <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>
      </TitleSortContainer>
      <ListHeader enableSort={true} />
      <ListContainer>
        {chats.map((item, index) => (
          <ChatCard key={index} chat={item} />
        ))}
      </ListContainer>
    </ChatColumnContainer>
  );
};

export default ChatColumn;
