import { useState, useEffect } from 'react'
import { ColorPicker, Checkbox, Flex } from 'antd'
import PropTypes from 'prop-types'

const ColorSelector = ({ value, onChange, disabled, required = false }) => {
  // Determine initial enabled state based on value
  const [colorEnabled, setColorEnabled] = useState(!!value)

  useEffect(() => {
    setColorEnabled(!!value)
  }, [value])

  const handleCheckboxChange = (e) => {
    const checked = e.target.checked
    setColorEnabled(checked)
    if (!checked) {
      onChange(null)
    } else if (checked && !value) {
      onChange('#000000')
    }
  }

  const handleColorChange = (color) => {
    onChange('#' + color.toHex())
  }

  return (
    <Flex gap={'middle'}>
      <ColorPicker
        showText
        disabledAlpha
        style={{ width: '100%', justifyContent: 'start' }}
        disabled={(!colorEnabled && !required) || disabled}
        value={value || '#000000'}
        onChange={handleColorChange}
      />
      {!required && (
        <Checkbox
          checked={colorEnabled}
          onChange={handleCheckboxChange}
          disabled={disabled}
        />
      )}
    </Flex>
  )
}

ColorSelector.propTypes = {
  value: PropTypes.string,
  onChange: PropTypes.func,
  disabled: PropTypes.bool,
  required: PropTypes.bool
}

export default ColorSelector
