import React, { useMemo } from "react";
import PropTypes from "prop-types";
import {
  ChatInfo,
  ChatCardContainer,
  Col,
  UserImage,
  UserImgWrapper,
  UserName,
  LastMessage,
  Line,
} from "./ChatCard.styled";
import { useHistory } from "react-router-dom";
import useScreenDimensions from "../../../hooks/useScreenDimensions";
import LittleOfferDetails from "./LittleOfferDetails/LittleOfferDetails";
import MobileOfferDetails from "./MobileOfferDetails/MobileOfferDetails";
import OfferLocation from "./OfferLocation/OfferLocation";
import ChatCommands from "./ChatCommands/ChatCommands";

const ChatCard = (props) => {
  const history = useHistory();
  const dimensions = useScreenDimensions();

  const chat = useMemo(() => {
    return props.chat;
  }, [props.chat]);

  const lastMessage = useMemo(() => {
    if (chat?.chat?.messages && chat?.chat?.messages?.length > 0) {
      return chat.chat.messages[chat.chat.messages.length - 1]?.text;
    }
    return "";
  }, [chat]);
  const routeToItem = () => {
    history.push(`/messages/${chat?.chat?._id}`);
  };
  return (
    <ChatCardContainer
      onClick={
        dimensions.width < 600 ? () => routeToItem(chat?.chat?._id) : () => {}
      }
    >
      <Col>
        <UserImgWrapper>
          <UserImage src={chat?.interlocutorData?.image} />
        </UserImgWrapper>

        <ChatInfo>
          <UserName>{chat?.interlocutorData?.name}</UserName>

          {/* Only shows on Mobile */}
          <MobileOfferDetails chat={chat} />
          {/* ^^^^^ */}

          <LastMessage>{lastMessage}</LastMessage>
          <OfferLocation chat={chat} />
        </ChatInfo>
      </Col>
      <Line />

      {/* Only shows on Desktop */}
      <LittleOfferDetails chat={chat} />
      {/* ^^^^^^^ */}

      <ChatCommands routeToItem={() => routeToItem(chat?.chat?._id)} />
    </ChatCardContainer>
  );
};

ChatCard.propTypes = {
  children: PropTypes.node,
  title: PropTypes.string,
  description: PropTypes.string,
  category: PropTypes.string,
  author: PropTypes.string,
  location: PropTypes.string,
  image: PropTypes.node,
  quantity: PropTypes.number,
  package: PropTypes.string,
  numberOfViews: PropTypes.number,
  halfwidth: PropTypes.bool,
  sponsored: PropTypes.bool,
  offer: PropTypes.any,
  pinned: PropTypes.bool,
  vertical: PropTypes.bool,
  chat: PropTypes.any,
};
ChatCard.defaultProps = {
  halfwidth: false,
  sponsored: false,
};

export default ChatCard;
