import React from 'react';
import Select from 'react-select';
import Tooltip from '../../../components/core/Tooltip';
import { displayProPopup } from '../../../Helper';
import { translate } from '../../../Helper';

const EcreSelectPro = ({
  id,
  label,
  options,
  value,
  onChange,
  width,
  classNamePrefix,
  isSearchable,
  placeholder,
  isMulti,
  tooltip,
  components,
  isOptionDisabled,
  marginTop, isPro = true,
  isDisabled = false,
  onSubscriptionClick,
}) => {
  const handleChange = (selectedOption) => {
    onChange(selectedOption); // Pass the selected option(s) to the parent component
  };

  const formatValue = (value) => {
    if (!options || !Array.isArray(options)) {
      console.error('Options should be an array', options);
      return isMulti ? [] : null;
    }

    if (isMulti) {
      // For multi-select, ensure value is an array of option objects
      return options.filter(option => value.some(v => v.value === option.value));
    } else {
      // For single select, find the option object
      return options.find(option => option.value === value) || null;
    }
  };

  return (
    <div className={`select-wrapper ${marginTop ? marginTop : ''}`}>
      <label htmlFor={id} className="ecre-text-sm ecre-font-medium ecre-block ecre-mb-2">
        <span className={`ecre-mr-2.5`}>{label}</span>
        {tooltip && <Tooltip className="ecre-align-[-2px]" content={tooltip} />}
      </label>
      <Select
        id={id}
        className={`echorewards-react-select ecre-max-w-${width}`}
        classNamePrefix={classNamePrefix}
        value={formatValue(value)}
        onChange={handleChange}
        options={options ? options : []}
        isSearchable={isSearchable}
        placeholder={placeholder}
        components={components}
        isMulti={isMulti}
        isDisabled={isDisabled}
        onSubscriptionClick={onSubscriptionClick}
        {...(!isPro && { isOptionDisabled })}
        {...(isPro && !ecreAdmin.is_woocommerce_subscriptions_active && (id == 'referral_coupon_type' || id == 'reward_type') && { isOptionDisabled })}
      />
    </div>
  );
};

export default EcreSelectPro;
