import { Badge, List } from "antd";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { setSelectedConversation } from "../../redux/messaging/messaging.actions";
import { selectSelectedConversation } from "../../redux/messaging/messaging.selectors";
import PhoneFormatter from "../../utils/PhoneFormatter";
import "./chat-conversation-list.styles.scss";

const mapStateToProps = createStructuredSelector({
  selectedConversation: selectSelectedConversation,
});

const mapDispatchToProps = (dispatch) => ({
  setSelectedConversation: (conversationId) =>
    dispatch(setSelectedConversation(conversationId)),
});

export function ChatConversationListComponent({
  conversationList,
  selectedConversation,
  setSelectedConversation,
}) {
  const { t } = useTranslation();

  return (
    <List
      bordered
      size="small"
      dataSource={conversationList}
      renderItem={(item) => (
        <List.Item
          onClick={() => setSelectedConversation(item.id)}
          className={`chat-list-item ${
            item.id === selectedConversation
              ? "chat-list-selected-conversation"
              : null
          }`}
        >
          <List.Item.Meta
            title={<PhoneFormatter>{item.phone_num}</PhoneFormatter>}
            description={
              item.job_conversations.length > 0 ? (
                <div>
                  {item.job_conversations.map(
                    (j) =>
                      `${j.job.ownr_fn || ""} ${j.job.ownr_ln || ""} ${
                        j.job.ownr_co_nm || ""
                      }`
                  )}
                </div>
              ) : (
                t("messaging.labels.nojobs")
              )
            }
          />
          <Badge count={item.messages_aggregate.aggregate.count || 0} />
        </List.Item>
      )}
    />
  );
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ChatConversationListComponent);
