import React from 'react';
import { Text, View, TouchableOpacity, StyleSheet } from 'react-native';
import type { ContentItem, FormProperty } from '../types';
import type { ContentViewItem } from '../store/contentModel';

interface FormCheckboxProps {
  element: ContentItem;
  contentItem: ContentViewItem;
  value: boolean;
  onChange: (value: string) => void;
  onBlur?: () => void;
  error?: string;
  touched?: boolean;
  disabled?: boolean;
}

export const FormCheckbox: React.FC<FormCheckboxProps> = ({
  element,
  value,
  onChange,
  onBlur,
  error,
  touched,
  disabled,
}) => {
  const properties = element.data as FormProperty;
  const styles = properties.styles || {};

  const label = properties.label || element.name;

  const handleToggle = () => {
    if (!disabled) {
      onChange(value ? '' : '1');
      if (onBlur) onBlur();
    }
  };

  return (
    <View
      style={{
        width: properties.styles.width || properties?.customStyles?.width,
      }}
    >
      <TouchableOpacity
        style={[
          properties.styles as any,
          properties.customStyles,
          { flexDirection: 'row', alignItems: 'center', gap: 6 },
        ]}
        onPress={handleToggle}
        disabled={disabled}
      >
        <View
          style={[
            // eslint-disable-next-line react-native/no-inline-styles
            {
              borderColor: error ? '#ff0000' : '#ccc',
              borderWidth: 2,
              borderRadius: 4,
              backgroundColor: value
                ? styles.backgroundColor || '#007AFF'
                : '#fff',
              width: 20,
              height: 20,
              justifyContent: 'center',
              alignItems: 'center',
            },
            disabled && formStyles.disabled,
          ]}
        >
          {value && (
            <Text style={[formStyles.checkmark, properties.labelStyle]}>✓</Text>
          )}
        </View>

        <View>
          <Text style={[properties.labelStyle]}>{label}</Text>
        </View>
      </TouchableOpacity>

      {error && touched && <Text style={formStyles.errorText}>{error}</Text>}
    </View>
  );
};

const formStyles = StyleSheet.create({
  container: {
    marginBottom: 16,
  },
  checkboxContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  checkbox: {
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  checkmark: {
    fontSize: 14,
    fontWeight: 'bold',
  },
  labelContainer: {
    flex: 1,
  },
  label: {
    fontSize: 16,
    fontWeight: '400',
  },
  required: {
    color: '#ff0000',
  },
  disabled: {
    opacity: 0.5,
  },
  errorText: {
    color: '#ff0000',
    fontSize: 12,
    marginTop: 4,
    marginLeft: 32,
  },
});
