import { FC, useState } from 'react';
import { useQueryClient } from 'react-query';
import { useNavigate } from 'react-router-dom';

import CloseIcon from '@material-hu/icons/material/Close';
import SearchIcon from '@material-hu/icons/material/Search';
import Container from '@material-hu/mui/Container';
import IconButton from '@material-hu/mui/IconButton';
import InputAdornment from '@material-hu/mui/InputAdornment';
import { useTheme } from '@material-hu/mui/styles';
import TextField from '@material-hu/mui/TextField';

import { orgChartRoutes } from 'src/pages/dashboard/orgChart/routes';
import { getOrgChartPeopleList } from 'src/services/orgChart';
import { User } from 'src/types/user';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { PeopleList } from 'src/components/dashboard/people/PeopleList';

import { orgChartKeys } from '../queries';

export type SearchBarProps = {
  isMobile?: boolean;
  onClose?: any;
};

const SearchBar: FC<SearchBarProps> = props => {
  const { isMobile = false, onClose } = props;

  const [query, setQuery] = useState('');
  const { t } = useLokaliseTranslation('people');
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const theme = useTheme();
  const elementsBg = theme.palette.new.background.elements.default;
  const layoutBg = theme.palette.new.background.layout.default;

  const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) =>
    setQuery(event.target.value);

  const handleSelect = async (user: User) => {
    const invalidateBossesPromise = queryClient.removeQueries(
      orgChartKeys.allBosses(),
    );
    const invalidateSubordinatesPromise = queryClient.removeQueries(
      orgChartKeys.allSubordinates(),
    );
    const invalidateBossPromise = queryClient.removeQueries(
      orgChartKeys.Boss(),
    );

    await Promise.all([
      invalidateBossesPromise,
      invalidateSubordinatesPromise,
      invalidateBossPromise,
    ]);

    navigate(orgChartRoutes.thread.detail(user.id));
  };

  return (
    <Container
      sx={{
        width: isMobile ? 'calc(100vw - 100px)' : '320px',
        mr: 2,
        backgroundColor: 'transparent',
        '& .MuiInputBase-root': {
          backgroundColor: layoutBg,
          borderRadius: '4px',
          height: isMobile ? '37px' : 'auto',
        },
      }}
    >
      <TextField
        variant="outlined"
        placeholder={t('SEARCH_CONTACTS')}
        value={query}
        onChange={handleInputChange}
        InputProps={{
          [isMobile ? 'endAdornment' : 'startAdornment']: (
            <InputAdornment position={isMobile ? 'end' : 'start'}>
              {!isMobile && <SearchIcon fontSize="small" />}
              {isMobile && (
                <IconButton
                  sx={{ p: 0 }}
                  onClick={onClose}
                >
                  <CloseIcon fontSize="small" />
                </IconButton>
              )}
            </InputAdornment>
          ),
        }}
        sx={{
          width: isMobile ? 'calc(100vw - 116px)' : '300px',
          p: 0,
          '& fieldset': {
            height: '40px',
            borderRadius: '4px',
            top: '-4px',
            transition: 'border 0.25s ease',
            '&:focus': {
              borderColor: 'inherit',
            },
          },
          '& input': {
            py: '6px',
          },
        }}
      />
      {query !== '' && (
        <Container
          sx={{
            height: '300px',
            width: isMobile ? 'calc(100vw - 100px)' : '300px',
            p: '0 !important',
            mb: -6,
            position: isMobile ? 'auto' : 'absolute',
            boxShadow: '0px 4px 8px rgba(0, 0, 0, 0.25)',
          }}
        >
          <PeopleList
            listContainerStyle={{
              backgroundColor: elementsBg,
            }}
            listSubHeaderStyle={{
              backgroundColor: elementsBg,
            }}
            limit={4}
            handleSelect={handleSelect}
            query={query}
            getUsersList={(q, page, limit) =>
              getOrgChartPeopleList(q, page, limit)
            }
            formTextField
          />
        </Container>
      )}
    </Container>
  );
};

export default SearchBar;
