import { type FC, useEffect } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';

import { IconPlus, IconSearch } from '@material-hu/icons/tabler';
import { useTheme } from '@material-hu/mui/styles';

import Button from '@material-hu/components/design-system/Buttons/Button';
import HuFormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import Stack from '@material-hu/mui/Stack';

import { queryClient } from 'src/config/react-query';
import { EVENTS_SOCKETS } from 'src/constants/sockets';
import { useSocket } from 'src/contexts/SocketContext';
import usePermissions from 'src/hooks/usePermissions';
import { CONVERSATIONS_LIST_CONTAINER } from 'src/pages/dashboard/Conversations/constants';
import { conversationsRoutes } from 'src/pages/dashboard/Conversations/routes';
import { type ConversationMessageSocket } from 'src/pages/dashboard/Conversations/types';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { UserPermissions } from 'src/utils/permissions';

import ConversationsList from './components/Conversations/ConversationsList';
import ConversationsSearch from './components/Conversations/ConversationsSearch';
import SidebarConversations from './components/shared/SidebarConversations';
import useHandlerEvents from './hooks/useHandlerEvents';
import useNewFeaturesModal from './hooks/useNewFeaturesModal';
import { conversationKeys } from './queries';

const { CHATS_V2_CREATE_CONVERSATION } = UserPermissions;
const Conversations: FC = () => {
  const { t } = useLokaliseTranslation(['chat']);
  const navigate = useNavigate();
  const { modal } = useNewFeaturesModal();
  const theme = useTheme();
  const socket = useSocket();

  const { hasAll: canCreateConversation = true } = usePermissions([
    CHATS_V2_CREATE_CONVERSATION,
  ]);
  const { handleUpdatePropertiesConversation } = useHandlerEvents();

  const form = useForm({
    defaultValues: {
      filter: '',
    },
    mode: 'onChange',
  });

  const { filter } = form.watch();

  useEffect(() => {
    const handleSocketEvent = (data: ConversationMessageSocket) => {
      handleUpdatePropertiesConversation(data);
    };
    socket.listenEvent(
      EVENTS_SOCKETS.CHATS_V2_CHANNEL_INFO_CHANGED,
      handleSocketEvent,
    );

    return () => {
      socket.closeEvent(
        EVENTS_SOCKETS.CHATS_V2_CHANNEL_INFO_CHANGED,
        handleSocketEvent,
      );
    };
  }, [handleUpdatePropertiesConversation]);

  const handleOnClick = () => navigate(conversationsRoutes.new.conversation());

  useEffect(() => {
    return () => {
      queryClient.cancelQueries(conversationKeys.all());
    };
  }, []);

  return (
    <SidebarConversations
      title={t('chat:chats')}
      callToActionHeader={
        canCreateConversation && (
          <Button
            variant="secondary"
            startIcon={<IconPlus size={theme.spacing(2)} />}
            onClick={handleOnClick}
          >
            {t('general:new')}
          </Button>
        )
      }
    >
      <FormProvider {...form}>
        <HuFormInputClassic
          inputProps={{
            maxLength: 20,
            placeholder: t('general:search'),
            hasCounter: false,
            sx: {
              pt: 1,
              px: 2,
            },
            startAdornment: <IconSearch />,
          }}
          name="filter"
        />

        <Stack
          sx={{
            flex: 1,
            overflowY: 'hidden',
            [`& #${CONVERSATIONS_LIST_CONTAINER}`]: {
              scrollbarWidth: 'thin',
              scrollbarColor: 'transparent transparent',
              transition: 'scrollbar-color 0.2s linear',
            },
            [`& #${CONVERSATIONS_LIST_CONTAINER}:hover`]: {
              scrollbarColor: '#aaa transparent',
            },
          }}
        >
          {!filter && <ConversationsList />}
          {filter && <ConversationsSearch />}
        </Stack>
        {modal}
      </FormProvider>
    </SidebarConversations>
  );
};

export default Conversations;
