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

import Box from '@material-hu/mui/Box';
import CircularProgress from '@material-hu/mui/CircularProgress';
import FormControl from '@material-hu/mui/FormControl';
import FormHelperText from '@material-hu/mui/FormHelperText';
import InputLabel from '@material-hu/mui/InputLabel';
import MenuItem from '@material-hu/mui/MenuItem';
import Select from '@material-hu/mui/Select';

import { useTranslation } from 'src/pages/dashboard/recognitions/i18n';

export type SelectControlProps = {
  label?: string;
  name: string;
  options: any;
  control: any;
  isRequired?: boolean;
  sx?: any;
  defaultValue?: string;
  displayEmpty?: boolean;
  disabled?: boolean;
  isLoading?: boolean;
};

export const SelectControl: FC<SelectControlProps> = props => {
  const {
    label = null,
    name,
    options,
    control,
    isRequired = false,
    sx,
    defaultValue = '',
    displayEmpty = false,
    disabled = false,
    isLoading = false,
  } = props;

  const { t } = useTranslation();

  return (
    <FormControl
      variant="outlined"
      sx={{
        mt: 2,
        mb: 1,
        ...sx,
      }}
      fullWidth
      disabled={disabled}
    >
      {label && (
        <InputLabel>
          {label} {isRequired && <span>*</span>}
        </InputLabel>
      )}
      <Controller
        name={name}
        control={control}
        defaultValue={defaultValue}
        rules={{
          validate: value => {
            if (isRequired && value === '') {
              return t('REQUIRED_FIELD');
            }
            return true;
          },
        }}
        render={({ field, fieldState }) => (
          <>
            <Select
              label={label}
              error={Boolean(fieldState.error)}
              {...field}
              displayEmpty={displayEmpty}
            >
              {label && !isLoading && (
                <MenuItem
                  disabled
                  value=""
                >
                  Seleccione {label.toLowerCase()}
                </MenuItem>
              )}
              {!label && !isLoading && <MenuItem value="">{t('ALL')}</MenuItem>}
              {isLoading && (
                <Box sx={{ textAlign: 'center', mt: 1 }}>
                  <CircularProgress color="primary" />
                </Box>
              )}
              {options.map((option, index) => (
                <MenuItem
                  key={index}
                  value={option.id}
                >
                  {t(option.name)}
                </MenuItem>
              ))}
            </Select>
            {fieldState.error && (
              <FormHelperText sx={{ color: '#f44336' }}>
                {fieldState.error.message}
              </FormHelperText>
            )}
          </>
        )}
      />
    </FormControl>
  );
};

export default SelectControl;
