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

const ArchivingStatusBar = ({ status }) => {
  const { t } = useTranslations()
  const [archiving, setArchiving] = useState('raady_to_arhive')
  const [archivedOrders, setArchivedOrders] = useState(0);
  const [totalArchivedOrder, setTotalArchiveOrders] = useState(0);
  const [percentage, setPercentage] = useState(0)

  const calculatePercentage = (queuedOrders, totalOrders) => {
    if (totalOrders === 0) return 0 // Avoid division by zero
    return Math.round((queuedOrders / totalOrders) * 100)
  }

  const fetchArchivingStatus = async () => {
    try {
      const archivingStatus = await makeApiRequest('archive-post', 'POST')
      console.log(archivingStatus)
      if (archivingStatus.success) {
        const { archiveLoop } = archivingStatus.data
        if (archiveLoop) {
          setTimeout(() => fetchArchivingStatus(), 1000)
        }
      } else {
        console.log('failed to archive')
        setArchiving('archive__failed')
      }
    } catch (error) {
      console.log('Error fetching archive status:', error)
      setArchiving('archive__failed')
    }
  }

  const fetchRemoteArchivingStatus = async () => {
    const remoteArchivingStatus = await makeApiRequest('remote-archive-status', 'POST')
    console.log('remote archiving status', remoteArchivingStatus)
    if (remoteArchivingStatus.success) {
      const { archivedOrders, totalArchivedOrder } = remoteArchivingStatus.data
      setArchivedOrders(archivedOrders)
      setTotalArchiveOrders(totalArchivedOrder)
      setPercentage(calculatePercentage(archivedOrders, totalArchivedOrder))
      console.log(archivedOrders, totalArchivedOrder)
      if (archivedOrders === parseInt(totalArchivedOrder)) {
        if (0 !== archivedOrders && 0 !== parseInt(totalArchivedOrder)) {
          setTimeout(function () {
            setArchiving('archiving__complete')
          }, 3000)
        }
      } else {
        setTimeout(() => fetchRemoteArchivingStatus(), 1000)
      }
    }
  }

  const initiliazeAchiveProcess = async () => {
    const isBackgroundRunning = await makeApiRequest('check-background-archiving', 'POST')
    console.log(isBackgroundRunning)
    if (isBackgroundRunning.success) {
      setArchiving('archiving__start')
    }
  }

  useEffect(() => {
    initiliazeAchiveProcess()
  }, [])

  useEffect(() => {
    if ('archiving__start' === archiving) {
      fetchArchivingStatus()
      fetchRemoteArchivingStatus()
    }
  }, [archiving])

  return (
    <>
      {('raady_to_arhive' === archiving ||
        'archiving__complete' === archiving ||
        'archive__failed' === archiving) && (
        <div className='archiving-status arcm-pl-6 md:arcm-pl-5 arcm-pr-4  md:arcm-pr-5 -arcm-ml-6 arcm-py-2 arcm-bg-white'>
          <div className='archiving-status__bar arcm-flex arcm-gap-1.5'>
            <div className='text arcm-w-full arcm-flex arcm-flex-wrap arcm-items-center arcm-justify-between arcm-gap-x-1.5'>
              <div className='arcm-text-gray-900 arcm-text-sm arcm-font-normal'>
                {'archiving__complete' === archiving && t('archive_complete')}
                {'archive__failed' === archiving &&
                  t('no_order_queued_archive')}
              </div>
            </div>
          </div>
        </div>
      )}
      {'archiving__start' === archiving && (
        <div className='archiving-status arcm-pl-6 md:arcm-pl-5 arcm-pr-4  md:arcm-pr-5 -arcm-ml-6 arcm-py-2 arcm-bg-white'>
          <div className='archiving-status__bar arcm-flex arcm-gap-1.5'>
            <div className='icon'>
              <svg
                xmlns='http://www.w3.org/2000/svg'
                width='20'
                height='20'
                viewBox='0 0 20 20'
                fill='none'
              >
                <path
                  d='M3.99523 3.99523C3.40633 3.40633 3.40076 2.44063 4.07144 1.94689C5.51268 0.885882 7.22049 0.225371 9.01983 0.0481524C11.3222 -0.178615 13.6321 0.399965 15.5557 1.68531C17.4794 2.97065 18.8978 4.88323 19.5694 7.09716C20.241 9.3111 20.1242 11.6894 19.2388 13.8268C18.3534 15.9643 16.7543 17.7286 14.714 18.8192C12.6736 19.9098 10.3182 20.2592 8.04908 19.8078C5.77998 19.3565 3.73758 18.1323 2.26988 16.3439C1.12287 14.9463 0.382319 13.2716 0.113464 11.5023C-0.0116492 10.6789 0.67514 9.99997 1.50797 9.99998C2.34079 9.99998 2.99965 10.6828 3.17809 11.4963C3.41277 12.5662 3.89745 13.5731 4.60123 14.4306C5.62628 15.6797 7.05271 16.5346 8.63746 16.8499C10.2222 17.1651 11.8672 16.9211 13.2923 16.1594C14.7173 15.3977 15.8341 14.1655 16.4524 12.6727C17.0708 11.1799 17.1524 9.51887 16.6833 7.97264C16.2143 6.42641 15.2236 5.09066 13.8801 4.19296C12.5367 3.29527 10.9235 2.89119 9.31544 3.04956C8.2114 3.1583 7.1567 3.52756 6.23423 4.11814C5.53284 4.56718 4.58412 4.58412 3.99523 3.99523Z'
                  fill='#3858E9'
                >
                  <animateTransform
                    attributeName='transform'
                    type='rotate'
                    from='0 10 10'
                    to='360 10 10'
                    dur='2s'
                    repeatCount='indefinite'
                  />
                </path>
              </svg>
            </div>
            <div className='text arcm-w-full arcm-flex arcm-flex-wrap arcm-items-center arcm-justify-between arcm-gap-x-1.5'>
              <div className='arcm-text-gray-900 arcm-text-sm arcm-font-normal'>
                {t('data_being_archived')} <strong>({percentage}%)</strong>
              </div>
              <a className='arcm-inline-flex arcm-items-center arcm-cursor-pointer arcm-gap-1 arcm-text-[#3858e9] arcm-text-sm arcm-font-semibold arcm-underline arcm-transition-all hover:arcm-no-underline hover:arcm-text-[#3858e9]'>
                {t('view_more_details')}
                <span className=' arcm-inline-block'>
                  <svg
                    xmlns='http://www.w3.org/2000/svg'
                    width='6'
                    height='10'
                    viewBox='0 0 6 10'
                    fill='none'
                  >
                    <path
                      fill-rule='evenodd'
                      clip-rule='evenodd'
                      d='M0.209376 9.76983C-0.0777189 9.47125 -0.0684094 8.99647 0.230169 8.70937L4.16792 5L0.230169 1.29062C-0.0684099 1.00353 -0.0777193 0.528747 0.209376 0.230167C0.496471 -0.0684109 0.971253 -0.0777207 1.26983 0.209374L5.76983 4.45937C5.91689 4.60078 6 4.79599 6 5C6 5.20401 5.91689 5.39922 5.76983 5.54062L1.26983 9.79062C0.971254 10.0777 0.496471 10.0684 0.209376 9.76983Z'
                      fill='#3858E9'
                    />
                  </svg>
                </span>
              </a>
            </div>
          </div>
        </div>
      )}
    </>
  )
}

export default ArchivingStatusBar
