import { useEffect, useRef } from 'react'
import { Select } from 'antd'
import PropTypes from 'prop-types'

const CustomSelect = ({
  placeholder,
  disabled,
  options = [],
  value,
  onChange,
  ...rest
}) => {
  const prevOptionsRef = useRef(options)

  useEffect(() => {
    // Check if options have changed
    const optionsChanged =
      JSON.stringify(prevOptionsRef.current) !== JSON.stringify(options)

    if (optionsChanged && value !== undefined && value !== null) {
      // Check if current value exists in new options
      const valueExists =
        Array.isArray(options) &&
        options.some((option) => option.value === value)

      // If value doesn't exist in new options, clear it
      if (!valueExists && onChange) {
        onChange(undefined)
      }
    }

    // Update the ref with current options
    prevOptionsRef.current = options
  }, [options, value, onChange])

  return (
    <Select
      placeholder={placeholder}
      disabled={disabled}
      options={Array.isArray(options) ? options : []}
      value={value}
      onChange={onChange}
      {...rest}
    />
  )
}

CustomSelect.propTypes = {
  placeholder: PropTypes.string,
  disabled: PropTypes.bool,
  options: PropTypes.array,
  value: PropTypes.any,
  onChange: PropTypes.func
}

export default CustomSelect
