import React from 'react';
import { Checkbox, FormControlLabel, FormControl, FormHelperText, Box, Typography } from '@mui/material';
import { useFormContext, Controller } from 'react-hook-form';
import { type IFormLayoutType } from './index';

export interface CheckboxFormFieldProps extends IFormLayoutType {
  name: string;
  label: string;
  defaultValue?: boolean;
  required?: boolean;
  disabled?: boolean;
  helperText?: string;
  color?: 'primary' | 'secondary' | 'default';
}

export function CheckboxFormField({
  name,
  label,
  defaultValue = false,
  required = false,
  disabled = false,
  layout = 'vertical',
  helperText,
  color = 'primary',
}: CheckboxFormFieldProps) {
  const { control, formState: { errors } } = useFormContext();
  const error = errors[name];
  const isHorizontal = layout === 'horizontal';

  const checkbox = (
    <Controller
      name={name}
      control={control}
      defaultValue={defaultValue}
      render={({ field }) => (
        <FormControl error={!!error} disabled={disabled}>
          <FormControlLabel
            control={
              <Checkbox
                {...field}
                checked={field.value || false}
                onChange={(e) => field.onChange(e.target.checked)}
                color={color}
                required={required}
              />
            }
            label={isHorizontal ? undefined : label}
          />
          {(error?.message || helperText) && (
            <FormHelperText>
              {error?.message as string || helperText}
            </FormHelperText>
          )}
        </FormControl>
      )}
    />
  );

  if (isHorizontal) {
    return (
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <Typography variant="subtitle1" sx={{ minWidth: 120, pt: 1 }}>
          {label}
          {required && <span style={{ color: 'red' }}>*</span>}
        </Typography>
        <Box sx={{ flex: 1 }}>
          {checkbox}
        </Box>
      </Box>
    );
  }

  return checkbox;
}