import { ArrowUpTrayIcon } from '@heroicons/react/24/outline';
import { useDispatch } from 'react-redux';
import ProBadge from '../../../../../components/ProBadge';
import { changeBadgeSettingProperties } from '../../../../../features/badges/badgesSlice';
import isProActive from '../../../../../utils/isProActive';

const UploadBadge = () => {
  const dispatch = useDispatch();
  const isPro = isProActive();

  const openMediaLibrary = () => {
    if (!isPro) return;

    const mediaUploader = wp.media({
      title: 'Select or Upload Badge',
      button: {
        text: 'Select This Image',
      },
      multiple: false,
    });

    mediaUploader.on('select', () => {
      dispatch(changeBadgeSettingProperties({ name: 'type', value: 'upload' }));
      const attachment = mediaUploader.state().get('selection').first().toJSON();
      dispatch(changeBadgeSettingProperties({ name: 'uploadedUrl', value: attachment.url }));
    });

    mediaUploader.open();
  };

  return (
    <div className='wmx-relative'>
      <button
        disabled={!isPro}
        className='wmx-capitalize wmx-flex wmx-gap-2 wmx-items-center wmx-rounded-lg wmx-bg-primary wmx-text-white wmx-outline-none wmx-shadow-none wmx-px-4 wmx-text-base wmx-font-semibold wmx-py-2 disabled:wmx-cursor-not-allowed disabled:wmx-opacity-60'
        onClick={openMediaLibrary}
      >
        Upload Image <ArrowUpTrayIcon className='wmx-size-5 wmx-text-white' />
      </button>
      <ProBadge />
    </div>
  );
};

export default UploadBadge;
