import React, { useState, useEffect } from 'react'
import dayjs from 'dayjs'
import arcmIcons from '../Icons'
import { Ajax } from '../common'
import Modal from '../components/core/Modal'
import { DatePicker, Tooltip } from 'antd'
import FlexOrderPromoBanner from '../components/FlexOrderPromoBanner'
import { useTranslations } from '../hooks/useTranslation'

const ExportOrders = ({
  onvVeiwChange,
  AdminSettings,
  saveAdminSettings,
  setAdminSettings,
  saveBtnLoading,
  siteTotalOrder,
  ...props
}) => {
  const { t } = useTranslations();
  const [expostModalLoading, setExpostModalLoading] = useState(false)
  const [isOpenExportModal, setIsOpenExportModal] = useState(false)
  const [exportError, setExportError] = useState(false)
  const [exportModalTitle, setExportModalTitle] = useState(t('order_exporting'))
  const [wcOrderExportStatus, setWcOrderExportStatus] = useState('')
  const [percentage, setPercentage] = useState(0)
  const [exportFileName, setExportFileName] = useState(0)
  const [closeExportDownload, setCloseExportDownload] = useState(true)
  const [exportDownloadUrl, setExportDownloadUrl] = useState('')
  const [lastExportTime, setLastExportTime] = useState('')
  const [cancelExportBtnLoading, setCancelExportBtnLoading] = useState(false)
  const [isOpenExportCancelModal, setIsOpenExportCancelModal] = useState(false)
  const [isWide, setIsWide] = useState(window.innerWidth >= 1200)

  useEffect(() => {
    const handleResize = () => setIsWide(window.innerWidth >= 1200);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);
  const { order_export_option } = AdminSettings

  const exportOrder = async () => {
    try {
      setWcOrderExportStatus('start-export')
      const queryParams = {
        export_format: order_export_option.export_format,
        export_file_name: order_export_option.export_file_name,
        order_start_date: order_export_option.order_start_date || '',
        order_end_date: order_export_option.order_end_date || '',
        sort_type: order_export_option.sort_order,
        order_source: 'woocommerce'
      }

      const response = await Ajax.post('start_export_orders', queryParams)

      if (response.success) {
        if (0 === parseInt(response.data.total_order)) {
          alert(t('no_orders_found'))
          setWcOrderExportStatus('export-cancel')
          return
        }
        fetchExportingStatus()
      } else {
        // Handle case when backend returns success: false (e.g., no orders found)
        setWcOrderExportStatus('export-cancel')
        if (response.message) {
          alert(response.message)
        } else {
          alert(t('no_orders_found'))
        }
      }
    } catch (error) {
      console.error('Export error:', error)
      setExportError(true)
      setExportModalTitle(t('export_failed'))
      setWcOrderExportStatus('export-cancel')
    }
  }

  const downloadExportFile = () => {
    const a = document.createElement('a')
    a.href = exportDownloadUrl
    a.download = exportFileName + '.' + order_export_option.export_format || ''
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  }

  const formateLastExportDate = archivedDate => {
    if (!archivedDate) {
      return
    }

    const date = new Date(archivedDate)
    const formattedDate = date
      .toLocaleString('en-US', {
        day: '2-digit',
        month: 'short',
        year: 'numeric',
        hour: 'numeric',
        minute: '2-digit',
        hour12: true
      })
      .replace(',', '')
      .replace(',', ' |')

    return formattedDate
  }

  const fetchExportingStatus = async () => {
    const response = await Ajax.post('check_export_progress')
    if (response.success) {
      const jobs = response.data
      const jobIds = Object.keys(jobs)
      
      if (jobIds.length === 0) {
        // No jobs found, reset status
        setWcOrderExportStatus('export-cancel')
        setPercentage(0)
        return
      }
      
      let jobStauts = jobs[jobIds[0]]
      
      // Check if job status exists and is valid
      if (!jobStauts || !jobStauts.status) {
        setWcOrderExportStatus('export-cancel')
        setPercentage(0)
        return
      }
      
      setPercentage(parseInt(jobStauts.progress || 0))
      if ('processing' === jobStauts.status) {
        setTimeout(() => fetchExportingStatus(), 1000)
      } else {
        if (!exportFileName && jobStauts.file_name) {
          setExportFileName(jobStauts.file_name)
        }
        setCloseExportDownload(false)
        if (jobStauts.download_url) {
          setExportDownloadUrl(jobStauts.download_url)
        }
        if (jobStauts.updated_at) {
          setLastExportTime(formateLastExportDate(jobStauts.updated_at))
        }
        setTimeout(() => {
          if ('cancelled' === jobStauts.status) {
            setWcOrderExportStatus('export-cancel')
          } else if ('completed' === jobStauts.status) {
            setWcOrderExportStatus('export-complete')
          }
          setPercentage(0)
        }, 2000)
      }
    } else {
      // Handle case when check_progress fails
      setWcOrderExportStatus('export-cancel')
      setPercentage(0)
    }
  }

  const handelCancelExporting = async () => {
    setCancelExportBtnLoading(true)
    const response = await Ajax.post('cancel_exporting')
    if (response.success) {
      setWcOrderExportStatus('export-cancel')
      setPercentage(0)
      setCloseExportDownload(false)
      setCancelExportBtnLoading(false)
      handleExportCancelModal()
    }
  }

  const handleExportCancelModal = () => {
    setIsOpenExportCancelModal(!isOpenExportCancelModal)
  }

  useEffect(() => {
    if (exportError) {
      setExportModalTitle(t('export_failed_title'))
    } else {
      setExportModalTitle(t('export_success_title'))
    }
  }, [setExportError])

  return (
    <>
      <div className='archive-export-orders'>
        <button
          onClick={() => onvVeiwChange('dashboard_settings')}
          className='arcm-mb-4 arcm-flex arcm-items-center arcm-justify-center arcm-text-[#3858e9] arcm-text-sm arcm-font-semibold'
        >
          <div className='icon arcm-mr-2'>{arcmIcons.arrowLeft}</div>
          {t('go_to_dashboard')}
        </button>

        <div className="arcm-flex arcm-flex-col xl:arcm-flex-row arcm-gap-8 arcm-items-start arcm-mt-8 md:arcm-mt-12">
          <div className='archive-export-orders__form arcm-flex-1'>
            <div className='arcm-title arcm-mb-6'>
              <h5 className='arcm-text-gray-800 arcm-text-xl arcm-font-bold arcm-mb-1.5'>
                {t('export_orders_title')}
              </h5>
              <p className='arcm-text-gray-500 arcm-text-sm arcm-font-normal'>
                {t('export_orders_desc')}
              </p>
            </div>

          <div className='arcm-form-group arcm-mb-6'>
            <label className='arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-block arcm-mb-3'>
              <span className='arcm-mr-2 arcm-align-[2px]'>
                {t('select_date_range')}
              </span>
              <Tooltip
                className='arcm-text-sm'
                placement='top'
                title={t('date_range_tooltip')}
                color='#fff'
              >
                {arcmIcons.info}
              </Tooltip>
            </label>
            <div className='arcm-select-fields arcm-max-w-[489px] arcm-flex arcm-flex-col sm:arcm-flex-row arcm-flex-wrap sm:arcm-items-center arcm-gap-3.5'>
              <div className='arcm-select-fields__date arcm-flex-grow'>
                <div className='arcm-label arcm-text-gray-900 arcm-text-sm arcm-font-normal arcm-mb-1.5'>
                  {t('from')}
                </div>
                <DatePicker
                  className='arcm-min-w-full !arcm-text-gray-900'
                  placeholder={t('select_date')}
                  defaultValue={
                    order_export_option.order_start_date
                      ? dayjs(order_export_option.order_start_date, 'YYYY-MM-DD')
                      : ''
                  }
                  onChange={(date, dateString) => {
                    order_export_option.order_start_date = dateString
                    setAdminSettings({
                      ...AdminSettings,
                      order_export_option: order_export_option
                    })
                  }}
                />
              </div>

              <div className='arcm-divider arcm-hidden sm:arcm-block arcm-text-black arcm-text-sm arcm-font-medium arcm-whitespace-nowrap arcm-mt-[20px]'>
                -
              </div>

              <div className='arcm-select-fields__date arcm-flex-grow'>
                <div className='arcm-label arcm-text-gray-900 arcm-text-sm arcm-font-normal arcm-mb-1.5'>
                  {t('to')}
                </div>
                <DatePicker
                  className='arcm-min-w-full !arcm-text-gray-900'
                  placeholder={t('select_date')}
                  defaultValue={
                    order_export_option.order_end_date
                      ? dayjs(order_export_option.order_end_date, 'YYYY-MM-DD')
                      : ''
                  }
                  onChange={(date, dateString) => {
                    order_export_option.order_end_date = dateString
                    setAdminSettings({
                      ...AdminSettings,
                      order_export_option: order_export_option
                    })
                  }}
                />
              </div>
            </div>
            <p className='arcm-text-gray-600 arcm-text-xs arcm-font-normal arcm-mt-3'>
              {t('date_range_note')}
            </p>
          </div>

          <div className='arcm-form-group arcm-mb-6'>
            <label className='arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-block arcm-mb-3'>
              <span className='arcm-mr-2 arcm-align-[2px]'>
                {t('export_file_name')}
              </span>
              <Tooltip
                className='arcm-text-sm'
                placement='top'
                title={t('file_name_tooltip')}
                color='#fff'
              >
                {arcmIcons.info}
              </Tooltip>
            </label>
            <input
              type='text'
              value={order_export_option.export_file_name}
              className='arcm-max-w-[489px] !arcm-p-4 !arcm-bg-white !arcm-rounded-lg !arcm-border !arcm-border-gray-400 !arcm-text-gray-900 !arcm-text-sm !arcm-font-normal !arcm-shadow-none placeholder:!arcm-text-gray-400 !arcm-w-full'
              onChange={e => {
                order_export_option.export_file_name = e.target.value
                setAdminSettings({
                  ...AdminSettings,
                  order_export_option: order_export_option
                })
              }}
            />
          </div>

          <div className='arcm-form-group arcm-mb-6'>
            <label className='arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-block arcm-mb-3'>
              <span className='arcm-mr-2 arcm-align-[2px]'>{t('sort_orders')}</span>
              <Tooltip
                className='arcm-text-sm'
                placement='top'
                title={t('sort_orders_tooltip')}
                color='#fff'
              >
                {arcmIcons.info}
              </Tooltip>
            </label>

            <div className='arcm-radio-fields arcm-flex arcm-flex-wrap arcm-items-center arcm-gap-4 arcm-max-w-[332px]'>
              <label
                htmlFor='arcm-ascending'
                className="arcm-grow arcm-shrink arcm-basis-[158px] arcm-radio arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-p-5 arcm-pl-[52px] arcm-bg-white arcm-rounded-lg arcm-relative arcm-min-w-[158px] arcm-items-center arcm-inline-flex arcm-cursor-pointer after:arcm-content-[''] after:arcm-w-5 after:arcm-h-5 after:arcm-border after:arcm-rounded-full after:arcm-border-gray-400 after:arcm-absolute after:arcm-left-6 before:arcm-content-[''] before:arcm-w-3 before:arcm-h-3 before:arcm-rounded-full before:arcm-bg-transparent before:arcm-absolute before:arcm-left-7 arcm-transition-all has-[:checked]:before:arcm-bg-[#3858e9] has-[:checked]:after:arcm-border-[#3858e9]"
              >
                <input
                  type='radio'
                  id='arcm-ascending'
                  className='!arcm-hidden'
                  name='sort-orders'
                  value='ASC'
                  checked={order_export_option.sort_order === 'ASC'}
                  onChange={e => {
                    order_export_option.sort_order = e.target.value
                    setAdminSettings({
                      ...AdminSettings,
                      order_export_option: order_export_option
                    })
                  }}
                />
                <span>{t('ascending')}</span>
              </label>

              <label
                htmlFor='arcm-descending'
                className="arcm-grow arcm-shrink arcm-basis-[158px] arcm-radio arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-p-5 arcm-pl-[52px] arcm-bg-white arcm-rounded-lg arcm-relative arcm-min-w-[158px] arcm-items-center arcm-inline-flex arcm-cursor-pointer after:arcm-content-[''] after:arcm-w-5 after:arcm-h-5 after:arcm-border after:arcm-rounded-full after:arcm-border-gray-400 after:arcm-absolute after:arcm-left-6 before:arcm-content-[''] before:arcm-w-3 before:arcm-h-3 before:arcm-rounded-full before:arcm-bg-transparent before:arcm-absolute before:arcm-left-7 arcm-transition-all has-[:checked]:before:arcm-bg-[#3858e9] has-[:checked]:after:arcm-border-[#3858e9]"
              >
                <input
                  type='radio'
                  id='arcm-descending'
                  name='sort-orders'
                  className='!arcm-hidden'
                  value='DESC'
                  checked={order_export_option.sort_order === 'DESC'}
                  onChange={e => {
                    order_export_option.sort_order = e.target.value
                    setAdminSettings({
                      ...AdminSettings,
                      order_export_option: order_export_option
                    })
                  }}
                />
                <span>{t('descending')}</span>
              </label>
            </div>
          </div>

          <div className='arcm-form-group arcm-mb-4'>
            <label className='arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-block arcm-mb-3'>
              <span className='arcm-mr-2 arcm-align-[2px]'>
                {t('select_export_format')}
              </span>
              <Tooltip
                className='arcm-text-sm'
                placement='top'
                title={t('export_format_tooltip')}
                color='#fff'
              >
                {arcmIcons.info}
              </Tooltip>
            </label>

            <div className='arcm-radio-fields arcm-flex arcm-flex-wrap arcm-items-center arcm-gap-4 arcm-max-w-[680px]'>
              {['csv', 'json', 'xml'].map(format => (
                <label
                  key={format}
                  htmlFor={`arcm-${format}`}
                  className="arcm-grow arcm-shrink arcm-basis-[158px] arcm-radio arcm-text-gray-900 arcm-text-sm arcm-font-medium arcm-p-5 arcm-pl-[52px] arcm-bg-white arcm-rounded-lg arcm-relative arcm-min-w-[158px] arcm-items-center arcm-inline-flex arcm-cursor-pointer after:arcm-content-[''] after:arcm-w-5 after:arcm-h-5 after:arcm-border after:arcm-rounded-full after:arcm-border-gray-400 after:arcm-absolute after:arcm-left-6 before:arcm-content-[''] before:arcm-w-3 before:arcm-h-3 before:arcm-rounded-full before:arcm-bg-transparent before:arcm-absolute before:arcm-left-7 arcm-transition-all has-[:checked]:before:arcm-bg-[#3858e9] has-[:checked]:after:arcm-border-[#3858e9]"
                >
                  <input
                    type='radio'
                    id={`arcm-${format}`}
                    name='export-format'
                    className='!arcm-hidden'
                    value={format}
                    checked={order_export_option.export_format === format}
                    onChange={e => {
                      order_export_option.export_format = e.target.value
                      setAdminSettings({
                        ...AdminSettings,
                        order_export_option: order_export_option
                      })
                    }}
                  />
                  <span>{format.toUpperCase()}</span>
                </label>
              ))}
            </div>
          </div>

          {wcOrderExportStatus === 'start-export' && (
            <div className='arcm-bg-white arcm-p-6 arcm-mb-4 arcm-rounded-md'>
              <div className='arcm-text-gray-800 arcm-text-lg sm:arcm-text-xl arcm-font-bold arcm-mb-1.5'>
                {t('exporting_progress').replace('(%s)', `(${percentage})`)}
              </div>
              <div className='archive-progress__bar arcm-mb-2 arcm-max-w-[411px] arcm-relative arcm-h-5 arcm-pr-[471px] arcm-bg-[#d8dee2] arcm-rounded arcm-overflow-hidden'>
                <div
                  className='archive-progress__bar-inner arcm-absolute arcm-top-0 arcm-left-0 arcm-h-full arcm-bg-emerald-500'
                  style={{ width: `${percentage}%` }}
                ></div>
              </div>
              <div className='arcm-text-gray-900 arcm-text-sm arcm-font-normal arcm-inline-flex arcm-items-center arcm-gap-1.5'>
                <span className='icon'>{arcmIcons.spinning}</span>
                {t('woocommerce_orders')}
              </div>
              <div className='btn-box arcm-mt-3'>
                <button
                  onClick={handleExportCancelModal}
                  className='arcm-text-[#EF4444] arcm-text-sm arcm-font-semibold arcm-min-w-[140px] arcm-px-4 arcm-py-2.5 arcm-rounded-lg arcm-border arcm-border-[#EF4444] arcm-bg-white arcm-transition-all hover:arcm-bg-[#F44336] hover:arcm-text-white'
                >
                  {t('cancel')}
                </button>
              </div>

              <div className='arcm-text-gray-900 arcm-text-sm arcm-font-normal arcm-mt-3'>
                {t('background_process_notice').replace('%s', 'exporting')}
              </div>
            </div>
          )}

          {wcOrderExportStatus === 'export-complete' && !closeExportDownload && (
            <div className='arcm-w-full arcm-bg-white arcm-mb-6 arcm-rounded-lg arcm-shadow-sm arcm-border arcm-border-gray-200 arcm-relative'>
              <button
                onClick={() => setCloseExportDownload(true)}
                className='arcm-absolute arcm-top-3 arcm-right-3 arcm-text-gray-500 arcm-hover:bg-gray-100 arcm-rounded arcm-p-1 arcm-transition-colors arcm-cursor-pointer'
              >
                {arcmIcons.close}
              </button>
              <div className='arcm-p-4'>
                                 <h2 className='arcm-text-gray-900 arcm-font-semibold arcm-mb-2'>
                   {t('exporting_completed')}
                 </h2>
                <p className='arcm-text-black arcm-text-sm arcm-mb-4 arcm-font-medium'>
                  {exportFileName}
                </p>
                <p className='arcm-text-gray-500 arcm-text-xs arcm-mb-4'>
                  {lastExportTime}
                </p>

                <button
                  onClick={downloadExportFile}
                  className='arcm-flex arcm-items-center arcm-bg-white arcm-hover:bg-blue-100 arcm-border arcm-border-blue-200 arcm-rounded-md arcm-px-3 arcm-py-2 arcm-text-blue-600 arcm-text-sm arcm-font-medium arcm-transition-colors arcm-cursor-pointer'
                >
                  {arcmIcons.download}
                  <span className='arcm-ml-2'>{t('download_file')}</span>
                </button>
              </div>
            </div>
          )}

          {wcOrderExportStatus !== 'start-export' && (
            <button
              onClick={exportOrder}
              className='arcm-text-white arcm-text-xs sm:arcm-text-sm arcm-font-semibold arcm-px-4 arcm-py-3 arcm-border arcm-border-[#3858e9] arcm-rounded-lg arcm-justify-center arcm-items-center arcm-gap-2 arcm-inline-flex arcm-transition-all arcm-group arcm-bg-[#3858e9] hover:arcm-bg-white hover:arcm-text-[#3858e9]'
            >
              <span className='icon'>{arcmIcons.export}</span>
              <span>{t('export_orders_btn')}</span>
            </button>
          )}
          {window?.archm_admin?.flexorder_promo?.show_permanent_banner && !isWide && (
            <div className="arcm-mt-8">
              <FlexOrderPromoBanner 
                showAsButtons={true}
                showClose={false}
                variant="horizontal"
                customTitle={t('flexorder.banner.try_live_sync')}
                customSubtitle={t('flexorder.banner.efficient_way')}
                bullets={[
                  t('flexorder.banner.bullet_1'),
                  t('flexorder.banner.bullet_2'),
                  t('flexorder.banner.bullet_3'),
                  t('flexorder.banner.bullet_4')
                ]}
                activeOrders={siteTotalOrder || 0}
              />
            </div>
          )}
        </div>

        {window?.archm_admin?.flexorder_promo?.show_permanent_banner && isWide && (
          <div className="arcm-w-full lg:!arcm-w-[485px] arcm-shrink-0">
            <FlexOrderPromoBanner 
              showAsButtons={true}
              showClose={false}
              variant="vertical"
              customTitle={t('flexorder.banner.try_live_sync')}
              customSubtitle={t('flexorder.banner.efficient_way')}
              bullets={[
                t('flexorder.banner.bullet_1'),
                t('flexorder.banner.bullet_2'),
                t('flexorder.banner.bullet_3'),
                t('flexorder.banner.bullet_4')
              ]}
              activeOrders={siteTotalOrder || 0}
            />
          </div>
        )}
      </div></div>

      {/* Cancel exporting modal */}
      <Modal
        openModal={isOpenExportCancelModal}
        toggleModal={handleExportCancelModal}
        outerClick={false}
      >
        {{
                     header: (
             <h2 className='arcm-text-lg arcm-font-bold arcm-text-black arcm-text-left arcm-mb-4'>
               {t('cancel_export_title')}
             </h2>
           ),
          body: (
                         <div className='arcm-text-left arcm-mb-6'>
               <p className='arcm-text-gray-900 arcm-text-base arcm-font-semibold'>
                 {t('cancel_export_confirm')}
               </p>
              <div className='btn-box arcm-flex arcm-flex-wrap arcm-gap-4 arcm-mt-6'>
                <button
                  onClick={handelCancelExporting}
                  disabled={cancelExportBtnLoading}
                  className='arcm-flex-grow arcm-text-white arcm-text-sm arcm-font-semibold arcm-min-w-[120px] arcm-px-4 arcm-py-2.5 arcm-rounded-lg arcm-bg-red-500 arcm-transition-all hover:arcm-bg-red-400 disabled:arcm-opacity-50 disabled:arcm-cursor-not-allowed arcm-flex arcm-items-center arcm-justify-center arcm-gap-2'
                >
                  {cancelExportBtnLoading ? (
                    <>
                      <span className='icon'>{arcmIcons.spinning}</span>
                      {t('cancelling')}
                    </>
                                     ) : (
                     t('cancel_exporting')
                   )}
                </button>
                <button
                  onClick={handleExportCancelModal}
                  disabled={cancelExportBtnLoading}
                  className='arcm-flex-grow arcm-text-gray-900 arcm-text-sm arcm-font-semibold arcm-min-w-[120px] arcm-px-4 arcm-py-2.5 arcm-rounded-lg arcm-bg-slate-100 arcm-transition-all hover:arcm-bg-slate-300'
                >
                  {t('close')}
                </button>
              </div>
            </div>
          )
        }}
      </Modal>
    </>
  )
}

export default ExportOrders