import React, { useState, useEffect } from 'react'
import { Ajax } from '../common'
import { useTranslations } from '../hooks/useTranslation'

const LockIcon = () => (
  <svg
    xmlns='http://www.w3.org/2000/svg'
    viewBox='0 0 24 24'
    fill='none'
    stroke='currentColor'
    strokeWidth='2'
    strokeLinecap='round'
    strokeLinejoin='round'
    className='arcm-w-5 arcm-h-5'
  >
    <rect x='3' y='11' width='18' height='11' rx='2' ry='2'></rect>
    <path d='M7 11V7a5 5 0 0 1 10 0v4'></path>
  </svg>
)

const LicenseManager = () => {
  const { t } = useTranslations();
  const [licenseKey, setLicenseKey] = useState(
    archm_admin.archm_settings.pro_license_key
  )
  const [licenseInanceId, setLicenseInanceId] = useState(
    archm_admin.archm_settings.pro_instance_id
  )
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [licenseStatus, setLicenseStatus] = useState(archm_admin.archm_settings.pro_license_key_status)

  const activateLicense = async () => {
    if (!licenseKey) {
      setError(t('please_enter_license'))
      return
    }

    setLoading(true)
    setError('')
    setSuccess('')

    try {
      const response = await fetch(
        'https://api.lemonsqueezy.com/v1/licenses/activate',
        {
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            license_key: licenseKey,
            instance_name: archm_admin.home_url
          })
        }
      )

      if (!response.ok) {
        throw new Error(t('license_activation_failed'))
      }

      const licenseInfo = await response.json()
      console.log(licenseInfo)
      const data = new FormData()
      data.append('action', 'archm_license_activate')
      data.append('nonce', archm_admin.nonce)
      data.append('license_key', licenseInfo.license_key.key)
      data.append('license_key_status', licenseInfo.license_key.status)
      data.append('instance_id', licenseInfo.instance.id)

      const statusUpdate = await fetch(archm_admin.ajax_url, {
        method: 'POST',
        body: data
      })

      if (statusUpdate.ok) {
        setSuccess(t('license_activated'))
        setLicenseStatus('active')
        setLicenseKey(licenseInfo.license_key.key)
      }
    } catch (err) {
      setError(t('failed_to_activate'))
    } finally {
      setLoading(false)
    }
  }

  const deActivateLicense = async () => {
    setLoading(true)
    setError('')
    setSuccess('')

    try {
      const response = await fetch(
        'https://api.lemonsqueezy.com/v1/licenses/deactivate ',
        {
          method: 'POST',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            license_key: licenseKey,
            instance_id: licenseInanceId
          })
        }
      )

      if (!response.ok) {
        throw new Error(t('license_deactivation_failed'))
      }

      const licenseInfo = await response.json()
      console.log(licenseInfo)
      const data = new FormData()
      data.append('action', 'archm_license_deactivate')
      data.append('nonce', archm_admin.nonce)
      data.append('license_action', 'deactivate')

      const statusUpdate = await fetch(archm_admin.ajax_url, {
        method: 'POST',
        body: data
      })

      if (statusUpdate.ok) {
        setSuccess(t('license_deactivated'))
        setLicenseStatus('inactive')
      }
    } catch (err) {
      setError(t('failed_to_deactivate'))
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    console.log(archm_admin)
    let status = archm_admin.archm_settings.pro_license_key_status
    setLicenseStatus(status)
    if('expired' === status || 'disabled' === status){
      setError(t('license_expired_disabled').replace('%s', status))
    }
  }, [])

  return (
    <div className='arcm-min-h-screen arcm-bg-gray-100'>
      <div className='arcm-p-8'>
        <h2 className='arcm-text-xl arcm-text-gray-700 arcm-mb-6'>
          {t('license_settings')}
        </h2>

        <div className='arcm-bg-white arcm-p-6 arcm-rounded arcm-shadow-sm'>
          <div className='arcm-flex arcm-items-center arcm-gap-2 arcm-mb-4'>
            <span className='arcm-text-blue-500'>
              <LockIcon />
            </span>
            <h3 className='arcm-text-lg arcm-font-medium'>{t('activate_license')}</h3>
          </div>

          <p className='arcm-text-gray-600 arcm-mb-8'>
            {t('activate_description').replace('%s', <span className='arcm-font-medium'>ArchiveMaster Pro</span>)}
          </p>

          <div className='arcm-flex arcm-gap-4'>
            <div className='arcm-flex-1'>
              <div className='arcm-relative'>
                <div className='arcm-absolute arcm-inset-y-0 arcm-left-3 arcm-flex arcm-items-center arcm-pointer-events-none arcm-text-gray-400'>
                  <LockIcon />
                </div>
                <input
                  type='text'
                  value={licenseKey}
                  onChange={e => setLicenseKey(e.target.value)}
                  placeholder={t('enter_license_key')}
                  className='arcm-w-full arcm-pl-10 arcm-pr-4 arcm-py-2 arcm-border arcm-border-gray-300 arcm-rounded arcm-focus:ring-2 arcm-focus:ring-blue-500 arcm-focus:border-blue-500 arcm-outline-none'
                />
              </div>
            </div>
            {('inactive' === licenseStatus || 'expired' === licenseStatus || 'disabled' === licenseStatus || !licenseStatus) && (
              <button
                onClick={activateLicense}
                disabled={loading}
                className='arcm-px-6 arcm-py-2 arcm-bg-blue-500 arcm-text-white arcm-rounded arcm-hover:bg-blue-600 arcm-focus:ring-2 arcm-focus:ring-blue-500 arcm-focus:ring-offset-2 arcm-disabled:opacity-50 arcm-disabled:cursor-not-allowed arcm-transition-colors'
              >
                {loading ? t('activating') : t('activate_license')}
              </button>
            )}
            {('active' === licenseStatus) && (
              <button
                onClick={deActivateLicense}
                disabled={loading}
                className='arcm-px-6 arcm-py-2 arcm-bg-red-500 arcm-text-white arcm-rounded arcm-hover:bg-blue-600 arcm-focus:ring-2 arcm-focus:ring-blue-500 arcm-focus:ring-offset-2 arcm-disabled:opacity-50 arcm-disabled:cursor-not-allowed arcm-transition-colors'
              >
                {loading ? t('deactivating') : t('deactivate_license')}
              </button>
            )}
          </div>

          {error && (
            <div className='arcm-mt-4 arcm-p-3 arcm-bg-red-50 arcm-text-red-600 arcm-rounded'>
              {error}
            </div>
          )}

          {success && (
            <div className='arcm-mt-4 arcm-p-3 arcm-bg-green-50 arcm-text-green-600 arcm-rounded'>
              {success}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default LicenseManager