import { useMemo, useState } from 'react';
import { useQuery } from 'react-query';

import Stack from '@material-hu/mui/Stack';
import { useTheme } from '@material-hu/mui/styles';
import TextField from '@material-hu/mui/TextField';
import Typography from '@material-hu/mui/Typography';

import HuUserAvatar from '@material-hu/components/composed-components/UserAvatar';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuFormAutocomplete from '@material-hu/components/design-system/Inputs/Autocomplete/form';
import HuFormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';

import { profileKeys } from 'src/pages/dashboard/profile/queries';
import { getPublicUsers } from 'src/services/users';
import { type User } from 'src/types/user';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName } from 'src/utils/userUtils';

import { useShiftsSelectionActions } from '../../../contexts/ShiftsSelectionContext';
import { shiftFormFields } from '../../../form';

import ShiftColorSelect from './ShiftColorSelect';

type UserOption = {
  label: string;
  value: number;
  userInfo: User;
};

type Props = {
  isAssigningDayOff?: boolean;
  isCreatingTemplate?: boolean;
};

const GeneralDataSection = ({
  isAssigningDayOff = false,
  isCreatingTemplate = false,
}: Props) => {
  const [search, setSearch] = useState('');
  const { t } = useLokaliseTranslation(['shifts', 'general']);
  const { palette } = useTheme();
  const { selectedDates, selectedCells } = useShiftsSelectionActions();

  const { data: users, isLoading: isLoadingUsers } = useQuery(
    profileKeys.userList(search),
    () => getPublicUsers({ page: 1, limit: 30, search }),
    {
      select: data => data.data.items,
      staleTime: 1000 * 60 * 2,
    },
  );

  const collaboratorsOptions = useMemo(() => {
    const userList = users || [];
    return userList.reduce(
      (acc: UserOption[], currentUser: User) =>
        acc.find(user => user.value === currentUser.id)
          ? acc
          : [
              ...acc,
              {
                label: getFullName(currentUser),
                value: currentUser.id,
                userInfo: currentUser,
              },
            ],
      [],
    );
  }, [users]);

  return (
    <>
      <Typography
        variant="globalM"
        sx={{ fontWeight: 'fontWeightSemiBold' }}
      >
        {t('general:general_data')}
      </Typography>
      <HuCardContainer
        sx={{
          backgroundColor: palette.new.background.elements.grey,
          border: 'unset',
          mb: 1,
          overflow: 'visible',
        }}
        fullWidth
      >
        {!isCreatingTemplate && (
          <>
            {selectedDates && selectedDates.size > 0 && (
              <Stack>
                <Typography
                  variant="globalS"
                  sx={{
                    fontWeight: 'fontWeightSemiBold',
                    mb: 0.5,
                    color: palette.new.text.neutral.default,
                  }}
                >
                  {t('general:collaborators')}
                </Typography>
                <TextField
                  value={t('shifts:multiple_collaborators')}
                  disabled
                  fullWidth
                  sx={{
                    '& .MuiOutlinedInput-root': {
                      backgroundColor: palette.new.background.elements.grey,
                      '& fieldset': {
                        borderColor: palette.new.border.neutral.default,
                      },
                      '&:hover fieldset': {
                        borderColor: palette.new.border.neutral.default,
                      },
                      '&.Mui-focused fieldset': {
                        borderColor: palette.new.border.neutral.default,
                      },
                      '&.Mui-disabled fieldset': {
                        borderColor: palette.new.border.neutral.default,
                      },
                    },
                  }}
                />
              </Stack>
            )}
            {selectedDates && selectedDates.size === 0 && (
              <HuFormAutocomplete
                name={shiftFormFields.collaborators}
                options={collaboratorsOptions}
                autocompleteProps={{
                  disabled: selectedCells.length > 0,
                  multiple: true,
                  placeholder: t('general:search'),
                  label: t('general:collaborators'),
                  noOptionsMessage: {
                    title: t('general:no_collaborators_found'),
                  },
                  limitTags: 2,
                  isOptionEqualToValue: (option, value) =>
                    option.value === value.value,
                  onInputChange: (_, value) => {
                    setSearch(value);
                  },
                  renderOption: (props, option) => {
                    return (
                      <li {...props}>
                        <HuUserAvatar
                          user={option.userInfo}
                          sx={{ width: '100%' }}
                          profileProps={{ showEmployeeInternalId: true }}
                        />
                      </li>
                    );
                  },
                  loading: isLoadingUsers,
                }}
                rules={{
                  required:
                    selectedCells.length === 0 &&
                    t('shift_validations.required_collaborator'),
                }}
              />
            )}
          </>
        )}
        {!isAssigningDayOff && (
          <Stack
            sx={{ alignItems: 'stretch', flexDirection: 'row', gap: 2, mt: 2 }}
          >
            <HuFormInputClassic
              name={shiftFormFields.shiftName}
              inputProps={{
                label: t('shift_name'),
                placeholder: t('shift_name_placeholder'),
                hasCounter: false,
              }}
            />
            <ShiftColorSelect />
          </Stack>
        )}
      </HuCardContainer>
    </>
  );
};

export default GeneralDataSection;
