import React from 'react';
import {
  Box,
  Typography,
  FormControlLabel,
  Switch,
  FormHelperText,
} from '@mui/material';
import { Controller, useFormContext } from 'react-hook-form';
import { useTranslation } from 'react-i18next';

export interface SwitchFormFieldProps {
  name: string;
  label: string;
  helperText?: string;
  defaultValue?: boolean;
  disabled?: boolean;
  required?: boolean;
  size?: 'small' | 'medium';
  color?: 'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning';
}

export const SwitchFormField: React.FC<SwitchFormFieldProps> = ({
  name,
  label,
  helperText,
  defaultValue = false,
  disabled = false,
  required = false,
  size = 'medium',
  color = 'primary',
}) => {
  const { control } = useFormContext();
  const { t } = useTranslation();

  return (
    <Box>
      <Controller
        name={name}
        control={control}
        defaultValue={defaultValue}
        rules={{
          required: required ? t('form.fieldRequired', { field: label }) : false,
        }}
        render={({ field, fieldState: { error } }) => (
          <>
            <FormControlLabel
              control={
                <Switch
                  checked={field.value || false}
                  onChange={field.onChange}
                  disabled={disabled}
                  size={size}
                  color={color}
                />
              }
              label={
                <Typography variant="body1">
                  {required && <span style={{ color: 'red' }}>*</span>}
                  {label}
                </Typography>
              }
            />
            {(error || helperText) && (
              <FormHelperText error={!!error}>
                {error?.message || helperText}
              </FormHelperText>
            )}
          </>
        )}
      />
    </Box>
  );
};