import React, { useState, useEffect } from 'react'
import { Tooltip, Select, Checkbox } from 'antd'
import { useTranslations } from '../hooks/useTranslation'
import Modal from './core/Modal'
import { makeApiRequest } from '../common'

const RelatedOrderMetadataArchiving = ({
  AdminSettings,
  setAdminSettings,
  isPro,
  falshDoor
}) => {
  const { t } = useTranslations()
  const [showModal, setShowModal] = useState(false)
  const [selectedMetadata, setSelectedMetadata] = useState(
    AdminSettings.related_order_metadata_selected || []
  )
  const [metaKeyOptions, setMetaKeyOptions] = useState([])
  const [loadingMetaKeys, setLoadingMetaKeys] = useState(false)

  const isEnabled = AdminSettings.enable_related_order_metadata_archiving || false

  // Sync selectedMetadata with AdminSettings
  useEffect(() => {
    if (AdminSettings.related_order_metadata_selected) {
      setSelectedMetadata(AdminSettings.related_order_metadata_selected)
    }
  }, [AdminSettings.related_order_metadata_selected])

  // Fetch custom order meta keys when enabled
  useEffect(() => {
    if (isEnabled && isPro) {
      fetchCustomOrderMetaKeys()
    }
  }, [isEnabled, isPro])

  const fetchCustomOrderMetaKeys = async () => {
    setLoadingMetaKeys(true)
    try {
      const response = await makeApiRequest('custom-order-meta-keys', 'GET')
      if (response.success && response.data) {
        setMetaKeyOptions(response.data)
      } else {
        console.error('Failed to fetch custom order meta keys:', response.message)
        setMetaKeyOptions([])
      }
    } catch (error) {
      console.error('Error fetching custom order meta keys:', error)
      setMetaKeyOptions([])
    } finally {
      setLoadingMetaKeys(false)
    }
  }

  const handleToggleChange = (e) => {
    if (!isPro) {
      falshDoor()
      e.preventDefault()
      return
    }

    // If trying to enable (currently disabled), show modal instead
    if (!isEnabled && e.target.checked) {
      e.preventDefault()
      setShowModal(true)
      return
    }

    // If trying to disable (currently enabled), allow direct disable
    if (isEnabled && !e.target.checked) {
      setAdminSettings({
        ...AdminSettings,
        enable_related_order_metadata_archiving: false
      })
    }
  }

  const handleEnable = () => {
    setAdminSettings({
      ...AdminSettings,
      enable_related_order_metadata_archiving: true
    })
    setShowModal(false)
  }

  const handleCancel = () => {
    setShowModal(false)
  }

  return (
    <>
      <div className='arcm-flex arcm-items-center arcm-gap-3 arcm-mt-4'>
        <label
          onClick={() => (!isPro ? falshDoor() : '')}
          htmlFor='enable-related-order-metadata-archiving'
          className='btn-switch arcm-inline-flex arcm-items-center arcm-cursor-pointer arcm-mb-2'
        >
          <div
            className={`arcm-flex arcm-items-center arcm-relative arcm-mr-2.5 ${
              !isPro ? 'arcm-cursor-not-allowed' : ''
            }`}
          >
            <input
              disabled={!isPro ? true : false}
              type='checkbox'
              checked={isEnabled}
              id='enable-related-order-metadata-archiving'
              onChange={handleToggleChange}
              className='arcm-sr-only arcm-peer'
            />
            <div className='dot-round arcm-bg-slate-200 arcm-w-12 arcm-h-7 arcm-rounded-[500px] arcm-transition-all peer-[:checked]:arcm-bg-[#3858E9]'></div>
            <div className='dot arcm-absolute arcm-start-1 arcm-top-1 arcm-bg-transparent arcm-w-5 arcm-h-5 arcm-border-4 arcm-border-white arcm-rounded-[500px] arcm-transition-transform peer-checked:arcm-bg-white peer-checked:arcm-translate-x-full rtl:peer-checked:-arcm-translate-x-full'></div>
          </div>
          <div className='arcm-text-black arcm-text-sm arcm-font-medium'>
            <span className='arcm-mr-1'>
              {t('enable_related_order_metadata_archiving')}
            </span>
            {!isPro && (
              <button className='arcm-px-1.5 btn-prolock arcm-inline-flex arcm-items-center arcm-pt-[3px] arcm-pb-[4px] arcm-bg-[#FFE9FE] arcm-rounded-[26px] arcm-text-[#4d1c4b] arcm-text-sm arcm-font-normal '>
                <span className='icon-wrap'>
                  <svg
                    xmlns='http://www.w3.org/2000/svg'
                    width='13'
                    height='11'
                    viewBox='0 0 13 11'
                    fill='none'
                  >
                    <path
                      d='M0.806113 7.65309C0.542977 5.94268 0.279841 4.23232 0.0167049 2.52191C-0.0416496 2.14276 0.389758 1.88417 0.696628 2.11434C1.51645 2.7292 2.33622 3.34402 3.15604 3.95889C3.42597 4.16133 3.81053 4.09545 3.99766 3.81471L6.04517 0.743421C6.26154 0.41886 6.73842 0.41886 6.95479 0.743421L9.0023 3.81471C9.18944 4.09545 9.574 4.16129 9.84392 3.95889C10.6637 3.34402 11.4835 2.7292 12.3033 2.11434C12.6102 1.88417 13.0416 2.14276 12.9833 2.52191C12.7202 4.23232 12.457 5.94268 12.1939 7.65309H0.806113Z'
                      fill='#F748F0'
                    />
                    <path
                      d='M11.6001 10.5H1.39974C1.07185 10.5 0.80603 10.2342 0.80603 9.90627V8.60205H12.1938V9.90627C12.1938 10.2342 11.9279 10.5 11.6001 10.5Z'
                      fill='#F748F0'
                    />
                  </svg>
                </span>
                <span className='text'>
                  {t('button.upgrade_text')}
                </span>
              </button>
            )}
            <Tooltip
              className='arcm-text-sm'
              placement='top'
              title={t('enable_related_order_metadata_archiving_tooltip')}
              color='#fff'
            >
              <span className='arcm-ml-2 icon arcm-inline-flex'>
                <svg
                  xmlns='http://www.w3.org/2000/svg'
                  width='14'
                  height='13'
                  viewBox='0 0 14 13'
                  fill='none'
                >
                  <path
                    fillRule='evenodd'
                    clipRule='evenodd'
                    d='M13.4001 6.49998C13.4001 10.0346 10.5347 12.9 7.0001 12.9C3.46548 12.9 0.600098 10.0346 0.600098 6.49998C0.600098 2.96535 3.46548 0.0999756 7.0001 0.0999756C10.5347 0.0999756 13.4001 2.96535 13.4001 6.49998ZM6.15157 4.05143C5.91725 4.28574 5.53736 4.28574 5.30304 4.05143C5.06873 3.81711 5.06873 3.43721 5.30304 3.2029C6.2403 2.26564 7.75989 2.26564 8.69715 3.2029C9.63441 4.14016 9.63441 5.65975 8.69715 6.59701C8.38317 6.911 8.00238 7.12048 7.6001 7.22404V7.49995C7.6001 7.83132 7.33147 8.09995 7.0001 8.09995C6.66873 8.09995 6.4001 7.83132 6.4001 7.49995V7.09995C6.4001 6.52372 6.85605 6.16258 7.26517 6.07055C7.47868 6.02252 7.68138 5.91573 7.84863 5.74848C8.31725 5.27985 8.31725 4.52006 7.84863 4.05143C7.38 3.5828 6.6202 3.5828 6.15157 4.05143ZM7.0001 10.5C7.44192 10.5 7.8001 10.1418 7.8001 9.69998C7.8001 9.25815 7.44192 8.89997 7.0001 8.89997C6.55827 8.89997 6.2001 9.25815 6.2001 9.69998C6.2001 10.1418 6.55827 10.5 7.0001 10.5Z'
                    fill='#D1D5DB'
                  />
                </svg>
              </span>
            </Tooltip>
          </div>
        </label>
      </div>

      {/* Search and Select Order Metadata Section - Only show when enabled */}
      {isEnabled && (
        <div 
          className='arcm-mt-4 arcm-flex arcm-flex-col'
          style={{
            padding: '16px',
            gap: '16px',
            borderRadius: '8px',
            backgroundColor: '#F9FAFB',
            maxWidth: '548px',
            width: '100%'
          }}
        >
          <h3 className='arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-m-0'>
            {t('search_and_select_order_metadata')}
          </h3>
          <Select
            mode='multiple'
            showSearch
            placeholder={t('start_typing')}
            value={selectedMetadata}
            onChange={(value) => {
              setSelectedMetadata(value)
              setAdminSettings({
                ...AdminSettings,
                related_order_metadata_selected: value
              })
            }}
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            className='arcm-w-full [&_.ant-select-selector]:!arcm-px-3 [&_.ant-select-selector]:!arcm-py-1.5'
            style={{
              width: '100%',
              '--ant-select-item-option-selected-color': 'transparent'
            }}
            options={metaKeyOptions}
            loading={loadingMetaKeys}
            notFoundContent={loadingMetaKeys ? t('loading_metadata') : t('no_custom_order_metadata_found')}
            dropdownRender={menu => (
              <div>
                <style>
                  {`
                    .ant-select-item-option-selected .ant-select-item-option-state {
                      display: none !important;
                    }
                    .ant-select-item-option .ant-select-item-option-state {
                      display: none !important;
                    }
                    .ant-select-item-option-disabled {
                      cursor: default !important;
                    }
                    .ant-select-item-option-disabled:hover {
                      background-color: transparent !important;
                    }
                  `}
                </style>
                {menu}
              </div>
            )}
            optionRender={option => (
              <div className='arcm-flex arcm-items-center arcm-w-full arcm-relative'>
                <div className='arcm-flex arcm-items-center arcm-gap-2 arcm-flex-1'>
                  <Checkbox
                    checked={selectedMetadata.includes(option.data.value)}
                    onChange={e => {
                      e.stopPropagation()
                      const newValues = e.target.checked
                        ? [...selectedMetadata, option.data.value]
                        : selectedMetadata.filter(val => val !== option.data.value)
                      setSelectedMetadata(newValues)
                      setAdminSettings({
                        ...AdminSettings,
                        related_order_metadata_selected: newValues
                      })
                    }}
                  />
                  <span>{option.data.label}</span>
                </div>
              </div>
            )}
            removeIcon={<span className='arcm-text-gray-400'>×</span>}
            tagRender={props => (
              <>
                <span className='arcm-bg-gray-100 arcm-text-[#374151] arcm-px-2 arcm-py-1 arcm-inline-flex arcm-items-center arcm-gap-2 arcm-mb-4'>
                  <span className='arcm-flex arcm-items-center arcm-gap-2'>
                    {props.label}
                  </span>
                  <span
                    className='arcm-cursor-pointer arcm-text-[#374151] hover:arcm-text-gray-600'
                    onClick={props.onClose}
                  >
                    ×
                  </span>
                </span>
                <span className='arcm-mx-2 arcm-text-gray-300'></span>
              </>
            )}
          />
        </div>
      )}

      <Modal openModal={showModal} toggleModal={handleCancel}>
        {{
          header: (
            <h5 className='arcm-text-gray-800 arcm-text-lg sm:arcm-text-xl arcm-font-bold'>
              {t('advanced_feature_use_carefully')}
            </h5>
          ),
          body: (
            <div className='arcm-mb-6 arcm-mt-4'>
              <p className='arcm-text-gray-700 arcm-text-sm arcm-font-normal arcm-leading-6 arcm-mb-4' style={{ fontFamily: 'Inter', fontWeight: 400, fontSize: '14px' }}>
                {t('advanced_feature_popup_text_1')}
              </p>
              <p className='arcm-text-gray-700 arcm-text-sm arcm-font-normal arcm-leading-6 arcm-mb-6' style={{ fontFamily: 'Inter', fontWeight: 400, fontSize: '14px' }}>
                {t('advanced_feature_popup_text_2')}{' '}
                <a
                  href='https://wppool.dev/docs/understanding-the-order-data-archiving/'
                  target='_blank'
                  rel='noopener noreferrer'
                  className='arcm-text-[#3858E9] arcm-underline hover:arcm-text-[#2643C7]'
                >
                  {t('read_the_documentation')}
                </a>
              </p>
              <div className='arcm-flex arcm-gap-3'>
                <button
                  onClick={handleEnable}
                  className='arcm-text-white arcm-text-sm arcm-font-semibold arcm-px-6 arcm-py-2.5 arcm-bg-[#F97316] arcm-rounded-lg arcm-transition-all hover:arcm-bg-[#EA580C] arcm-flex-1'
                >
                  {t('enable')}
                </button>
                <button
                  onClick={handleCancel}
                  className='arcm-text-gray-900 arcm-text-sm arcm-font-semibold arcm-px-6 arcm-py-2.5 arcm-border arcm-border-gray-200 arcm-rounded-lg arcm-bg-white arcm-transition-all hover:arcm-bg-[#F1F5F9] arcm-flex-1'
                >
                  {t('cancel')}
                </button>
              </div>
            </div>
          )
        }}
      </Modal>
    </>
  )
}

export default RelatedOrderMetadataArchiving

