import { useFormContext } from 'react-hook-form';

import { useDrawerV2 } from '@material-hu/hooks/useDrawerV2';
import { IconTrash, IconUsersGroup } from '@material-hu/icons/tabler';
import Button from '@material-hu/mui/Button';
import Divider from '@material-hu/mui/Divider';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';

import HuUserAvatar from '@material-hu/components/composed-components/UserAvatar';

import { type User } from 'src/types/user';
import { type SectionsManager } from 'src/types/vacations';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { usePeopleSelectionDrawer } from '../../hooks/usePeopleSelectionDrawer';

type Props = {
  type: SectionsManager;
  isManagerView?: boolean;
};

export const FormUserAutocompleteVacations = ({
  type,
  isManagerView = true,
}: Props) => {
  const { t } = useLokaliseTranslation('time_off');
  const form = useFormContext();
  const selectedUsers = form.watch('users');

  const {
    drawer: peopleSelectionDrawer,
    showDrawer: showPeopleSelectionDrawer,
  } = useDrawerV2(peopleSelectionDrawerArgs =>
    usePeopleSelectionDrawer({
      ...peopleSelectionDrawerArgs,
      type,
      isManagerView,
    }),
  );

  return (
    <>
      {peopleSelectionDrawer}
      <Stack sx={{ gap: 2 }}>
        <Stack sx={{ gap: 1 }}>
          {selectedUsers.map((user: User) => (
            <Stack
              key={user.employeeInternalId}
              sx={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
                gap: 1,
              }}
            >
              <HuUserAvatar
                user={user}
                profileProps={{ showEmployeeInternalId: true }}
                sx={{ maxWidth: 430 }}
              />
              <IconButton
                onClick={() => {
                  form.setValue(
                    'users',
                    selectedUsers.filter((u: User) => u.id !== user.id),
                  );
                }}
              >
                <IconTrash />
              </IconButton>
            </Stack>
          ))}
        </Stack>
        {selectedUsers.length > 0 && (
          <Divider
            sx={{
              borderColor: ({ palette }) => palette.new.border.neutral.default,
            }}
          />
        )}
        <Button
          onClick={showPeopleSelectionDrawer}
          size="large"
          variant="secondary"
          startIcon={<IconUsersGroup />}
        >
          {t('general:add_people')}
        </Button>
      </Stack>
    </>
  );
};

export default FormUserAutocompleteVacations;
