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

import CloseIcon from '@material-hu/icons/material/Close';
import Avatar from '@material-hu/mui/Avatar';
import Chip from '@material-hu/mui/Chip';
import Divider from '@material-hu/mui/Divider';
import Drawer from '@material-hu/mui/Drawer';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';
import { ArrowLeftIcon } from '@material-hu/mui/x-date-pickers';

import Button from '@material-hu/components/design-system/Buttons/Button';

import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName } from 'src/utils/userUtils';

import FormUserAutocomplete from 'src/components/FormInputs/FormUserAutocomplete';

import ExternalUserReviewerForm from './components/ExternalUserReviewerForm';
import ExternalUserReviewersAutocomplete from './components/ExternalUserReviewersAutocomplete';
import ReviewerSelectionMenu from './components/ReviewerSelectionMenu';
import { usePeerSelectComponent } from './usePeerSelectComponent';

export { hasSelectReviewType } from './utils';

export type PeerSelectComponentProps = {
  reviewedId: number;
  reviewerCount: number;
};

const PeerSelectComponent = ({
  reviewedId,
  reviewerCount,
}: PeerSelectComponentProps) => {
  const { t } = useLokaliseTranslation('performance');
  const {
    form,
    directions,
    open,
    isNewExternal,
    isExternal,
    reviewType,
    finalSelection,
    isLoading,
    isLoadingUpdateReviewersSelected,
    isDisabled,
    filter,
    setIsNewExternal,
    handleToggle,
    handleReset,
    handleGoBack,
    handleApply,
    handleRemoveUser,
  } = usePeerSelectComponent({ reviewedId, reviewerCount });

  return (
    <FormProvider {...form}>
      <ReviewerSelectionMenu
        directions={directions}
        onSelect={handleToggle}
      />
      <Drawer
        anchor="right"
        open={open}
        onClose={() => handleToggle(null)}
        sx={{ zIndex: 1300 }}
        PaperProps={{
          sx: {
            width: 420,
            px: 2,
            py: 3,
            borderTopLeftRadius: 16,
            borderBottomLeftRadius: 16,
          },
        }}
      >
        <Stack sx={{ height: '100%' }}>
          <Stack
            sx={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              alignItems: 'center',
            }}
          >
            {isNewExternal && (
              <IconButton
                aria-label={t('nominate_reviewers.go_back')}
                onClick={handleGoBack}
              >
                <ArrowLeftIcon />
              </IconButton>
            )}
            <Typography variant="h6">
              {t(
                `${isNewExternal ? 'add' : 'nominate_reviewers.reviewers_selection'}`,
                {
                  context: reviewType,
                },
              )}
            </Typography>
            <IconButton
              aria-label={t('general:close')}
              onClick={handleReset}
            >
              <CloseIcon />
            </IconButton>
          </Stack>
          {!isNewExternal && (
            <>
              <Divider sx={{ mt: 1, mb: 2 }} />
              <Stack sx={{ overflow: 'auto', flex: 1 }}>
                <Stack
                  sx={{
                    backgroundColor: 'new.background.elements.grey',
                    p: 2,
                    gap: 1,
                    borderRadius: 2,
                  }}
                >
                  <Typography variant="subtitle2">
                    {t('nominate_reviewers.your_selection')}
                  </Typography>
                  {!isExternal && (
                    <FormUserAutocomplete
                      name="reviewer"
                      filterOptions={options => filter(options)}
                      loading={isLoading}
                      textFieldProps={{
                        variant: 'outlined',
                        margin: 'dense',
                        placeholder: t('nominate_reviewers.search_name'),
                        sx: {
                          backgroundColor: 'background.paper',
                          borderRadius: 1,
                        },
                      }}
                    />
                  )}
                  {isExternal && (
                    <ExternalUserReviewersAutocomplete
                      name="reviewer"
                      loading={isLoading}
                      setIsNewExternal={setIsNewExternal}
                    />
                  )}
                  <Stack
                    sx={{
                      flexDirection: 'row',
                      gap: 1,
                      flexWrap: 'wrap',
                      maxWidth: '100%',
                    }}
                  >
                    {finalSelection.map(u => (
                      <Chip
                        key={u.id}
                        variant="outlined"
                        label={getFullName(u)}
                        avatar={<Avatar src={u.profilePicture || undefined} />}
                        onDelete={() => handleRemoveUser(u)}
                      />
                    ))}
                  </Stack>
                </Stack>
              </Stack>
            </>
          )}
          {isNewExternal && (
            <ExternalUserReviewerForm onCancel={handleGoBack} />
          )}
          {!isNewExternal && (
            <Stack
              sx={{
                flexDirection: 'row',
                justifyContent: 'space-between',
                gap: 1,
                pt: 1,
              }}
            >
              <Button
                onClick={handleReset}
                fullWidth
              >
                {t('general:cancel')}
              </Button>
              <Button
                disabled={isDisabled}
                onClick={handleApply}
                variant="contained"
                fullWidth
                loading={isLoadingUpdateReviewersSelected}
              >
                {t('nominate_reviewers.save_selection')}
              </Button>
            </Stack>
          )}
        </Stack>
      </Drawer>
    </FormProvider>
  );
};

export default PeerSelectComponent;
