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

import Box from '@material-hu/mui/Box';
import List from '@material-hu/mui/List';

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 { FormTextField } from 'src/components/FormInputs';
import ListWrapper from 'src/components/list/List';
import Scrollbar from 'src/components/Scrollbar';

import NewTicketDialog from './NewTicketDialog';
import TicketItem from './TicketItem';

export type TicketSearchProps = {};

const TicketSearch: FC<TicketSearchProps> = () => {
  const [topicSelected, setTopicSelected] = useState<Topic>(null);
  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 = (topic: Topic) => {
    setTopicSelected(topic);
    setValue('query', '');
  };

  const handleCancel = () => {
    setTopicSelected(null);
  };

  return (
    <>
      {topics && topicSelected !== null && (
        <NewTicketDialog
          open={topicSelected !== null}
          onClose={handleCancel}
          {...topicSelected}
        />
      )}
      <Box
        sx={{
          alignItems: 'center',
          backgroundColor: 'background.default',
          borderRadius: 22,
          display: 'flex',
          height: 44,
          px: 2,
          m: 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>
      <Scrollbar options={{ suppressScrollX: true }}>
        <ListWrapper
          isSuccess={!!topics}
          isLoading={isLoading}
          isEmpty={topics?.length === 0}
          sx={{
            position: 'relative',
            zIndex: 0,
          }}
        >
          <List>
            {topics?.map((topic: Topic) => (
              <TicketItem
                key={topic.id}
                topic={topic}
                onSelect={handleSelect}
              />
            ))}
          </List>
        </ListWrapper>
      </Scrollbar>
    </>
  );
};

export default TicketSearch;
