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

import { IconSearch } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';

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

import UsersList from 'src/pages/dashboard/Conversations/components/ConversationsNew/UsersList';
import {
  useGetUserList,
  useOpenConversation,
} from 'src/pages/dashboard/Conversations/hooks/useConversationsQueries';
import { conversationsRoutes } from 'src/pages/dashboard/Conversations/routes';
import { type ConversationUser } from 'src/pages/dashboard/Conversations/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import ButtonNewGroup from './components/ConversationsNew/ButtonNewGroup';
import CloseActionHeader from './components/shared/CloseActionHeader';
import SidebarConversations from './components/shared/SidebarConversations';

const ConversationsNewGeneric: FC = () => {
  const { t } = useLokaliseTranslation(['chat', 'general']);
  const navigate = useNavigate();

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

  const { members, hasNextPage, ...listWrapperProps } = useGetUserList({
    query: filter,
  });

  const openConversation = useOpenConversation();

  const handleOnClick = () => navigate(conversationsRoutes.conversations());

  const handleSelectMember = (member: ConversationUser) => {
    const users = [member.id];
    openConversation.mutate({ users });
  };

  return (
    <SidebarConversations
      title={t('chat:new_chat')}
      callToActionHeader={<CloseActionHeader onClose={handleOnClick} />}
    >
      <FormProvider {...form}>
        <HuFormInputClassic
          inputProps={{
            maxLength: 20,
            placeholder: t('general:search'),
            hasCounter: false,
            sx: {
              mt: 1,
              mb: 2,
              px: 2,
            },
            startAdornment: <IconSearch />,
          }}
          name="filter"
        />
        <ButtonNewGroup />
        <Stack sx={{ flex: 1, overflow: 'auto' }}>
          <UsersList
            members={members}
            hasNextPage={hasNextPage || false}
            listWrapperProps={listWrapperProps}
            onSelectMember={handleSelectMember}
          />
        </Stack>
      </FormProvider>
    </SidebarConversations>
  );
};

export default ConversationsNewGeneric;
