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

import Box from '@material-hu/mui/Box';
import FormHelperText from '@material-hu/mui/FormHelperText';
import ToggleButton from '@material-hu/mui/ToggleButton';
import ToggleButtonGroup from '@material-hu/mui/ToggleButtonGroup';
import Typography from '@material-hu/mui/Typography';

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

export type ToggleControlProps = {
  label: string;
  name: string;
  control?: Control;
  defaultValue?: any;
  isRequired?: boolean;
  isReadOnly?: boolean;
};

export const ToggleControl: FC<ToggleControlProps> = props => {
  const {
    label,
    name,
    control = null,
    defaultValue = null,
    isRequired = false,
    isReadOnly = false,
  } = props;

  const { t } = useTranslation();

  return (
    <Controller
      name={name}
      control={control}
      rules={{
        validate: value => {
          if (isRequired && value === '') {
            return t('REQUIRED_FIELD');
          }
          return true;
        },
      }}
      render={({ field, fieldState }) => (
        <>
          <Box
            sx={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              width: '100%',
              px: 2,
              my: 2,
            }}
          >
            <Typography
              variant="body1"
              sx={{
                width: '70%',
                textAlign: 'justify',
              }}
            >
              {label} {isRequired && <span>*</span>}
            </Typography>
            <ToggleButtonGroup
              exclusive
              value={field.value !== undefined ? field.value : defaultValue}
              color="primary"
              sx={{ height: '40px' }}
              onChange={(_, value) => field.onChange(value)}
              disabled={isReadOnly}
            >
              <ToggleButton
                value={true}
                sx={{
                  borderRadius: '4px',
                  p: 1,
                  width: '40px',
                }}
              >
                {t('YES')}
              </ToggleButton>
              <ToggleButton
                value={false}
                sx={{
                  borderRadius: '4px',
                  p: 1,
                  width: '40px',
                }}
              >
                {t('NO')}
              </ToggleButton>
            </ToggleButtonGroup>
          </Box>
          {fieldState.error && (
            <FormHelperText sx={{ color: '#f44336', pl: 2 }}>
              {fieldState.error.message}
            </FormHelperText>
          )}
        </>
      )}
    />
  );
};

export default ToggleControl;
