import { useState, useEffect } from 'react'
import { ColorPicker, Checkbox, Flex, Row, Col, Divider } 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())
  }

  const customPanelRender = (_, { components: { Picker, Presets } }) => (
    <Row
      justify='space-between'
      wrap={false}
      style={{ width: '420px' }}
      gap={8}
    >
      <Col span={12}>
        <Presets />
      </Col>
      <Divider type='vertical' style={{ height: 'auto', margin: '0 12px' }} />
      <Col flex='auto'>
        <Picker />
      </Col>
    </Row>
  )

  const presets = [
    {
      label: 'Flat',
      colors: [
        '#1ABC9C',
        '#16A085',
        '#2ECC71',
        '#27AE60',
        '#3498DB',
        '#2980B9',
        '#9B59B6',
        '#8E44AD',
        '#34495E',
        '#2C3E50',
        '#F1C40F',
        '#F39C12',
        '#E67E22',
        '#D35400',
        '#E74C3C',
        '#C0392B',
        '#ECF0F1',
        '#BDC3C7',
        '#95A5A6',
        '#7F8C8D',
        '#535a5b'
      ]
    },
    {
      label: 'Metro',
      colors: [
        '#A4C400',
        '#60A917',
        '#008A00',
        '#00ABA9',
        '#1BA1E2',
        '#0050EF',
        '#6A00FF',
        '#AA00FF',
        '#F472D0',
        '#D80073',
        '#A20025',
        '#E51400',
        '#FA6800',
        '#F0A30A',
        '#E3C800',
        '#825A2C',
        '#6D8764',
        '#647687',
        '#76608A',
        '#A0522D',
        '#1d2121'
      ]
    }
  ]

  return (
    <Flex gap={'middle'}>
      <ColorPicker
        showText
        disabledAlpha
        style={{ width: '100%', justifyContent: 'start' }}
        disabled={(!colorEnabled && !required) || disabled}
        value={value || '#000000'}
        onChange={handleColorChange}
        presets={presets}
        panelRender={customPanelRender}
        arrow={false}
        className='ant-input-outlined'
      />
      {!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
