import { FC, useEffect } from 'react';

import Box from '@material-hu/mui/Box';
import Card from '@material-hu/mui/Card';
import CardContent from '@material-hu/mui/CardContent';

import { EVENTS_SOCKETS } from 'src/constants/sockets';
import { useSocket } from 'src/contexts/SocketContext';
import useChat from 'src/hooks/queryHooks/chat';
import useGeneralError from 'src/hooks/useGeneralError';
import { uploadImage } from 'src/services/attachments';
import {
  updateGroupChatTitle,
  updateGroupChatPictureUrl,
} from 'src/services/chats';
import { ChatListItem } from 'src/types/chats';

import {
  ChatThreadInfoToolbar,
  ChatThreadInfoHeader,
  ChatThreadInfoActions,
  ChatThreadInfoParticipants,
  ChatThreadInfoFooter,
} from 'src/components/dashboard/chat/ChatThreadInfo';
import { useTranslation } from 'src/components/dashboard/chat/i18n';
import {
  chatKeys,
  setChatListData,
  updateAdmins,
} from 'src/components/dashboard/chat/queries';

export type ChatThreadInfoProps = {
  id: number;
  onClose: () => void;
};

const ChatThreadInfo: FC<ChatThreadInfoProps> = props => {
  const { id, onClose } = props;
  const showGeneralError = useGeneralError();
  const { t } = useTranslation();
  const socket = useSocket();

  const { data, isLoading } = useChat(chatKeys.detail(id), id);

  useEffect(() => {
    socket.listenEvent(EVENTS_SOCKETS.USERS_MADE_ADMINS, updateAdmins);

    return () => {
      socket.closeEvent(EVENTS_SOCKETS.USERS_MADE_ADMINS, updateAdmins);
    };
  }, [socket, id]);

  const handleSubmitImage = async image => {
    try {
      const { url } = await uploadImage(image);
      const { data: thread } = await updateGroupChatPictureUrl(id, url);
      setChatListData(Number(id), thread);
    } catch (err) {
      showGeneralError(err, t('ERROR_UPDATING_GROUP_IMAGE'));
    }
  };

  const handleSubmitTitle = async (title: string) => {
    try {
      const { data: thread } = await updateGroupChatTitle(id, title);
      setChatListData(Number(id), thread);
    } catch (err) {
      showGeneralError(err, t('ERROR_UPDATING_GROUP_TITLE'));
    }
  };

  const thread = data?.data || null;

  const sections = [
    {
      id: 'header',
      render: (renderThread: ChatListItem | null) => (
        <ChatThreadInfoHeader
          title={renderThread?.title}
          pictureUrl={renderThread?.pictureUrl}
          color={renderThread?.color}
          onSubmitImage={handleSubmitImage}
          onSubmitTitle={handleSubmitTitle}
          editable={renderThread?.isAdmin}
        />
      ),
    },
    {
      id: 'actions',
      render: () => <ChatThreadInfoActions />,
    },
    {
      id: 'participants',
      render: (renderThread: ChatListItem | null) => (
        <ChatThreadInfoParticipants editable={renderThread?.isAdmin} />
      ),
    },
    {
      id: 'footer',
      render: (renderThread: ChatListItem | null) => (
        <ChatThreadInfoFooter createdDate={renderThread.createdAt} />
      ),
    },
  ];

  return (
    <Box
      sx={{
        backgroundColor: 'background.default',
        display: 'flex',
        flexDirection: 'column',
        flexGrow: 1,
        width: '324px',
      }}
    >
      {!isLoading && thread && (
        <>
          <ChatThreadInfoToolbar onClose={onClose} />
          <Box
            sx={{
              overflowY: 'auto',
              overflowX: 'hidden',
              scrollbarWidth: 'thin',
            }}
          >
            {sections.map(section => (
              <Card
                key={section.id}
                square
                elevation={0}
                sx={{
                  mb: '10px',
                }}
              >
                <CardContent
                  sx={{
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'center',
                    height: '100%',
                    minHeight: '60px',
                    p: '0 !important',
                  }}
                >
                  {section.render(thread)}
                </CardContent>
              </Card>
            ))}
          </Box>
        </>
      )}
    </Box>
  );
};

export default ChatThreadInfo;
