import { FC } from 'react';
import { useFormContext, Controller } from 'react-hook-form';

import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import MenuItem from '@material-hu/mui/MenuItem';
import TextField from '@material-hu/mui/TextField';
import Typography from '@material-hu/mui/Typography';

import { CatalogueOption } from 'src/types/nemakEvents';

import { useTranslation } from '../i18n';

export type DropDownControllerProps = {
  name: string;
  label: string;
  dropdownValues?: Array<CatalogueOption | number>;
  errorName?: string;
};

const renderOption = (option: CatalogueOption | number) => {
  const isCatalogue = typeof option === 'object';
  const optionKey = isCatalogue ? option.FieldsCatalogueId : option;
  const optionLabel = isCatalogue ? option.FieldOption : option;
  return (
    <MenuItem
      key={optionKey}
      value={optionKey}
    >
      {optionLabel}
    </MenuItem>
  );
};

export const DropDownController: FC<DropDownControllerProps> = props => {
  const { name, label, dropdownValues, errorName = null } = props;

  const { t } = useTranslation();
  const {
    control,
    formState: { errors },
  } = useFormContext();

  return (
    <Controller
      key={name}
      name={name}
      control={control}
      rules={{ required: t('REQUIRED_FIELD') }}
      render={({ field }) => {
        return (
          <>
            <TextField
              key={name}
              select
              label={label}
              fullWidth
              margin="normal"
              {...field}
            >
              {dropdownValues?.map(renderOption)}
              {!dropdownValues && (
                <Box
                  sx={{
                    display: 'flex',
                    width: '100%',
                    justifyContent: 'center',
                    mt: 1,
                    overflow: 'hidden',
                  }}
                >
                  <CircularProgress />
                </Box>
              )}
            </TextField>
            {errors[errorName || name] && (
              <Box sx={{ mb: 1 }}>
                <Typography sx={{ color: 'red' }}>
                  {t('REQUIRED_FIELD')}
                </Typography>
              </Box>
            )}
          </>
        );
      }}
    />
  );
};

export default DropDownController;
