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

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();

  return (
    <Box>
      <Controller
        name={name}
        control={control}
        defaultValue={defaultValue}
        rules={{
          required: required ? `${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>
  );
};