import { FC, useState, useEffect } from 'react';
import { useForm, FormProvider } from 'react-hook-form';

import Box from '@material-hu/mui/Box';
import Dialog, { DialogProps } from '@material-hu/mui/Dialog';
import DialogContent from '@material-hu/mui/DialogContent';
import DialogTitle from '@material-hu/mui/DialogTitle';
import List from '@material-hu/mui/List';
import ListItem from '@material-hu/mui/ListItem';
import ListItemText from '@material-hu/mui/ListItemText';

import useTicket from 'src/hooks/queryHooks/ticket';
import SearchIcon from 'src/icons/Search';
import { useTranslation } from 'src/pages/dashboard/tickets/i18n';
import { Topic } from 'src/types/tickets';

import { TicketChatAvatar } from 'src/components/dashboard/chat/ChatAvatar';
import { FormTextField } from 'src/components/FormInputs';
import ListWrapper from 'src/components/list/List';

export type ChangeChannelDialogProps = DialogProps & {
  onChangeChannel: (topic: Topic) => void;
  topicId: number;
};

const ChangeChannelDialog: FC<ChangeChannelDialogProps> = props => {
  const { onChangeChannel, topicId, ...dialogProps } = props;

  const [topics, setTopics] = useState<any[]>([]);

  const { t } = useTranslation();

  const { ticketTopicData } = useTicket();

  const form = useForm({
    defaultValues: {
      query: '',
    },
  });

  const { watch, setValue } = form;

  const query = watch('query');

  const { data, isLoading } = ticketTopicData();

  useEffect(() => {
    const newTopics = data?.data.items.filter(topic => {
      const queries: string[] = query
        .trim()
        .split(' ')
        .filter(queryToFilter => queryToFilter?.length > 0)
        .map(queryToMap => queryToMap.toLowerCase());

      return queries.every(newQuery =>
        topic.name.toLowerCase().includes(newQuery),
      );
    });

    setTopics(newTopics);
  }, [data?.data, query]);

  const handleSelect = (index: number) => {
    setValue('query', '');
    onChangeChannel(topics[index]);
  };

  return (
    <Dialog {...dialogProps}>
      <DialogTitle>{t('CHANGE_CHANNEL')}</DialogTitle>
      <DialogContent>
        <Box
          sx={{
            alignItems: 'center',
            backgroundColor: 'background.default',
            borderRadius: 22,
            display: 'flex',
            height: 44,
            px: 2,
            mx: 1,
            position: 'sticky',
            top: '0px',
            zIndex: 1,
          }}
        >
          <SearchIcon
            color="action"
            fontSize="small"
          />
          <Box
            sx={{
              flexGrow: 1,
              m: 2,
            }}
          >
            <FormProvider {...form}>
              <form noValidate>
                <FormTextField
                  name="query"
                  ariaLabel={t('SEARCH_TOPICS')}
                  placeholder={t('SEARCH_TOPICS')}
                  fullWidth
                  sx={{
                    '& fieldset': {
                      borderColor: 'transparent !important',
                    },
                  }}
                />
              </form>
            </FormProvider>
          </Box>
        </Box>
        <ListWrapper
          isSuccess={!!topics}
          isLoading={isLoading}
          isEmpty={topics?.length === 0}
          sx={{
            mt: 2,
            position: 'relative',
            zIndex: 0,
          }}
        >
          <List>
            {topics?.map((topic: Topic, index: number) => {
              if (topic.id !== topicId) {
                return (
                  <ListItem
                    key={topic.id}
                    button
                    onClick={() => handleSelect(index)}
                  >
                    <TicketChatAvatar
                      topic={topic}
                      sx={{
                        height: 32,
                        width: 32,
                      }}
                    />
                    <ListItemText
                      primary={topic.name}
                      primaryTypographyProps={{
                        color: 'textPrimary',
                        noWrap: true,
                        variant: 'subtitle2',
                      }}
                    />
                  </ListItem>
                );
              }
              return null;
            })}
          </List>
        </ListWrapper>
      </DialogContent>
    </Dialog>
  );
};

export default ChangeChannelDialog;
