import React, { useState, useEffect, useRef, useMemo } from 'react'
import { useSearchParams, useLocation } from 'react-router-dom'
import arcmIcons from '../Icons'
import { makeApiRequest, Ajax } from '../common'
import { useTranslations } from '../hooks/useTranslation'
import { Link } from 'react-router-dom'
import Onboarding from '../views/Onboarding'
import ArchiveSettings from '../views/ArchiveSettings'
import AwsConfigure from '../views/AwsConfigure'
import CustomMySQLConfigure from '../views/CustomMySQLConfigure'
import Logs from '../views/Logs'
import Modal from '../components/core/Modal'
import ExportOrders from '../views/ExportOrders'
import connectionContext from '../context/connectionContext'
import PieChart from '../components/core/PieChart'
import BarChart from '../components/core/BarChart'
import NoticeBar from '../components/NoticeBar'
import FlexOrderPromoModal from '../components/FlexOrderPromoModal'
import FlexOrderPromoBanner from '../components/FlexOrderPromoBanner'
import { initMenuClickHandler, cleanupMenuClickHandler, getDashboardClickEventName } from '../utils/menuClickHandler'

const Settings = () => {
  const { t } = useTranslations()
  const location = useLocation()
  const [searchParams] = useSearchParams()
  const valueArchivedOrderPage = searchParams.get('value')
  const [isBgUnarchiving, setIsBgUnarchiving] = useState(false)
  const [isMissingArchiveData, setIsMissingArchiveData] = useState(false)
  const [isGoogleDriveConnected, setIsGoogleDriveConnected] = useState(false)
  const [isRecoveringData, setIsRecoveringData] = useState(false)
  const [showSuccessNotice, setShowSuccessNotice] = useState(false)

  const [isFlexOrderModalOpen, setIsFlexOrderModalOpen] = useState(false)
  const [isFlexOrderDashboardModalOpen, setIsFlexOrderDashboardModalOpen] = useState(window?.archm_admin?.flexorder_promo?.show_dashboard_modal || false)
  const [isFlexOrderBannerOpen, setIsFlexOrderBannerOpen] = useState(window?.archm_admin?.flexorder_promo?.show_banner || false)
  const [flexOrderActiveOrders, setFlexOrderActiveOrders] = useState(window?.archm_admin?.flexorder_promo?.active_orders || 0)

  const [isOnboardingComplete, setIsOnboardingComplete] = useState(false)
  const [AdminSettings, setAdminSettings] = useState(archm_admin.archm_settings)
  const [activeView, setActiveView] = useState('dashboard_settings')
  const [isOpen, setIsOpen] = useState(false)
  const [isArchiveFailedOpen, setIsArchiveFailedOpen] = useState(false)
  const [archiveFailMeassage, setArchiveFailMeassage] = useState('')
  const [archiving, setArchiving] = useState(false)
  const [awsConnection, setAwsConnection] = useState(false)
  const [customMySQLConnection, setCustomMySQLConnection] = useState(false)
  const [googleDriveConnection, setGoogleDriveConnection] = useState(
    archm_admin.google || false
  )
  const [initialLoading, setInitialLoading] = useState(false)
  const [archiveSettings, setArchiveSettings] = useState({})
  const [percentage, setPercentage] = useState(0)
  const [saveBtnLoading, setSaveBtnLoading] = useState(false)
  const [isPro, setIsPro] = useState('')
  const [isSqliteEnable, setIsSqliteEnable] = useState('')
  const [archivedOrders, setArchivedOrders] = useState(0)
  const [totalArchiveOrders, setTotalArchiveOrders] = useState(0)
  const [totalOrderToArchive, setTotalOrderToArchive] = useState(0)
  const [totalOrder, setTotalOrder] = useState(0)
  const [siteArchivedOrder, setSiteArchivedOrder] = useState(0)
  const [siteTotalOrder, setSiteTotalOrder] = useState(0)
  const [olderSchedule, setOlderSchedule] = useState(0)
  const [onBoardingLoad, setOnBoardingLoad] = useState(false)
  const [archivingDate, setArchivingDate] = useState('')
  const [isArchiveCancel, setIsArchiveCancel] = useState(false)
  const [isCancelled, setIsCancelled] = useState(false)
  const canceArchivelRef = useRef(false)
  const backgroundArchivelRef = useRef(false)
  const [lastArchiveDate, setLastArchviedate] = useState('')
  const [cancelBtnLoading, setCancelBtnLoading] = useState(false)
  const [startArchivingLoading, setStartArchivingLoading] = useState(false)
  const [settingOffTooltip, setSettingOffTooltip] = useState(false)
  const [rdsCredential, setRdsCredential] = useState({
    rds_dbname: '',
    rds_username: '',
    rds_password: '',
    rds_port: '',
    rds_endpoint: ''
  })
  const [customMySQLCredential, setCustomMySQLCredential] = useState({
    endpoint: '',
    username: '',
    password: '',
    port: '3306',
    database: ''
  })
  const [lastArchiveSettingsTab, setLastArchiveSettingsTab] = useState('archive_options')

  const activePlugins = window?.archm_admin?.active_plugins || {}

  const handleAwsconnection = status => {
    setAwsConnection(status)
  }

  const handleCustomMySQLConnection = status => {
    setCustomMySQLConnection(status)
  }

  const handleToggleModal = () => {
    setIsOpen(!isOpen)
  }

  const handleArchiveingChange = archive => {
    setArchiving(archive)
  }

  const handleArchiveFailedToggleModal = () => {
    setIsArchiveFailedOpen(!isArchiveFailedOpen)
  }

  const handleArchiveing = archive => {
    setArchiving(archive)
    setIsOpen(!isOpen)
  }

  const handleOnboardingComplete = status => {
    setIsOnboardingComplete(status)
  }

  const handelCancelArchiving = () => {
    // Set the cancel flag
    canceArchivelRef.current = true
    backgroundArchivelRef.current = true
    // Clean up and reset states
    handleArchiveingChange('archiving__cancel')
    setPercentage(0)
    setCancelBtnLoading(true)
  }

  const handelCancelArchivingModal = () => {
    setIsArchiveCancel(!isArchiveCancel)
    if ('archiving__cancel' === archiving) {
      canceArchivelRef.current = false
      backgroundArchivelRef.current = false
      setIsCancelled(false)
    }
  }

  const handleViewChange = view => {
    if (
      'dashboard_settings' === view &&
      (Object.entries(archiveSettings).length === 0 ||
        Object.entries(rdsCredential).length === 0)
    ) {
      handleDashboardView()
    }
    setActiveView(view)

    // Get the current hash (e.g., "#/value=archive_settings")
    let currentHash = window.location.hash

    // Remove 'value=archive_settings' from the hash
    let newHash = currentHash.replace(/[\?&]?value=archive_settings/, '')

    // Update the URL without reloading the page
    history.replaceState(
      null,
      '',
      window.location.pathname + window.location.search + newHash
    )
  }

  const saveAdminSettings = async () => {
    setSaveBtnLoading(true)
    console.log('AdminSettings', AdminSettings)
    const saveSettings = await makeApiRequest(
      'update-settings',
      'POST',
      AdminSettings
    )
    setSaveBtnLoading(false)
    if (true === saveSettings.success) {
      Object.assign(archm_admin.archm_settings, AdminSettings)
      setIsOnboardingComplete(true)
      handleArchiveingChange(false)
      Siz.success(t('settings_saved'), 4000)
    } else {
      Siz.error(t('failed_to_save_settings'), 4000)
    }
  }

  const handleArchiveViewSettings = () => {
    handleViewChange('dashboard_settings')
    handleArchiveingChange('archiving__start')
    handleToggleModal()
  }

  const handleDashboardView = async () => {
    setInitialLoading(true)
    console.log('rds connecton ', AdminSettings.rds_connected)
    console.log('aws connecton ', awsConnection)

    if (AdminSettings.rds_connected || awsConnection) {
      console.log('awsconnection or rds connected')
      handleAwsconnection(true)
      setRdsCredential({ ...AdminSettings.rds_credential })
    } else {
      console.log('awsconnection false')
      handleAwsconnection(false)
    }

    if (AdminSettings.cmysql_connected || customMySQLConnection) {
      console.log('custom mysql connection')
      handleCustomMySQLConnection(true)
      setCustomMySQLCredential({ ...AdminSettings.cmysql_credential })
    } else {
      console.log('custom mysql connection false')
      handleCustomMySQLConnection(false)
    }

    if ('default' !== archm_admin.archm_settings.archive_range) {
      handleOnboardingComplete(true)
      setArchivingOrderInfo({
        archive_range: AdminSettings.archive_range,
        archive_range_datetime: AdminSettings.archive_range_datetime
      })
    } else {
      try {
        const orders = await makeApiRequest('calculate-site-order', 'POST')
        console.log(orders)
        if (orders.success) {
          const { ordersToarchive, olderMonths, totalOrder } = orders.data
          setTotalOrderToArchive(parseInt(ordersToarchive))
          setTotalOrder(parseInt(totalOrder))
          setOlderSchedule(olderMonths)
        }
      } catch (error) {
        alert(error)
        return
      }
      setOnBoardingLoad(true)
    }

    setInitialLoading(false)
  }

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

  const fetchArchivingStatus = async () => {
     if (canceArchivelRef.current) {
      return
    }

    try {
      const archivingStatus = await makeApiRequest('archive-post', 'POST')
      console.log(archivingStatus)
      if (archivingStatus.success) {
        const { archiveLoop } = archivingStatus.data
        console.log('archive loop status:', archiveLoop)
        if (archiveLoop && !canceArchivelRef.current) {
          console.log('archive post call')
          setTimeout(() => fetchArchivingStatus(), 1000)
        }
        return true
      } else {
        // Handle error response (including 400 Bad Request when no orders to archive)
        console.log('Failed to archive:', archivingStatus.message)
        // Update UI state to show error
        setArchivingOrderInfo({
          archive_range: AdminSettings.archive_range,
          archive_range_datetime: AdminSettings.archive_range_datetime
        })
        handleArchiveingChange('archive__failed')
        canceArchivelRef.current = true
        setArchiveFailMeassage(archivingStatus.message)
        return false
      }
    } catch (error) {
      console.log('Error fetching archive status:', error)
      handleArchiveingChange('archive__failed')
      return false
    }
  }

  const fetchRemoteArchivingStatus = async () => {
    const remoteArchivingStatus = await makeApiRequest(
      'remote-archive-status',
      'POST'
    )
    console.log('remote archiving status', remoteArchivingStatus)
    if (remoteArchivingStatus.success) {
      const { archivedOrders, totalArchivedOrder, loop } =
        remoteArchivingStatus.data
      setArchivedOrders(archivedOrders)
      setTotalArchiveOrders(totalArchivedOrder)
      setPercentage(calculatePercentage(archivedOrders, totalArchivedOrder))
      console.log(archivedOrders, totalArchivedOrder)
      if (!loop) {
        setTimeout(function () {
          handleArchiveingChange('archiving__complete')
          setIsArchiveCancel(false)
          canceArchivelRef.current = false
          backgroundArchivelRef.current = false
          setIsCancelled(false)
          //handleViewChange('dashboard_settings')
        }, 3000)
      } else {
        if (!canceArchivelRef.current) {
          setTimeout(() => fetchRemoteArchivingStatus(), 1000)
        } else {
          cancelArchivingInBackground()
        }
      }
    }
  }

  const cancelArchivingInBackground = async () => {
    const archBgStatus = await makeApiRequest('cancel-archiving', 'POST')
    if (archBgStatus.success) {
      console.log('cancel background archiving')
      console.log(archBgStatus)
      if (backgroundArchivelRef.current) {
        const { archivedOrders, totalArchivedOrder } = archBgStatus.data
        setArchivedOrders(archivedOrders)
        setTotalArchiveOrders(totalArchivedOrder)
        setIsCancelled(true)
        setCancelBtnLoading(false)
      }
    }
  }

  const falshDoor = () => {
    if (isPro.value) return

    const popup = WPPOOL.Popup('archive_master')

    if (!popup) return false
    popup.show()
  }

  const setArchivingOrderInfo = async schedule => {
    try {
      const orders = await makeApiRequest(
        'site-order-byschecdule',
        'POST',
        schedule
      )
      console.log('after onboarding', orders)
      if (orders.success) {
        const { ordersToarchive, date, totalOrder, lastArchivedOrder } =
          orders.data
        setArchivingDate(date)
        setTotalOrder(parseInt(totalOrder))
        setTotalOrderToArchive(parseInt(ordersToarchive))
        setLastArchviedate(lastArchivedOrder)
      }
    } catch (error) {
      alert(error)
    }
  }

  const handleBackgorundArchiving = async () => {
    const isBgArchiveRunning = await makeApiRequest(
      'check-background-archiving',
      'POST'
    )
    console.log('Background process status', isBgArchiveRunning)
    if (isBgArchiveRunning.success) {
      setStartArchivingLoading(true)
      setArchiving('archiving__start')
    }
  }

  const getSiteOrderInfo = async () => {
    const siteOrderInfo = await makeApiRequest('orders-info', 'POST')
    console.log('site order info:', siteOrderInfo)
    if (siteOrderInfo.success) {
      const { archived_order, total_order } = siteOrderInfo.data
      setSiteArchivedOrder(parseInt(archived_order))
      setSiteTotalOrder(parseInt(total_order))
    }
  }

  const formateLastArchivedDate = 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 redirectProPage = () => {
    const url = 'https://archivemaster.pro/'
    window.open(url, '_blank')
  }

  const checkBgUnnarchiving = async () => {
    const response = await Ajax.post('check_bg_archiving')
    console.log('check unarchiving background process', response)
    if (response.success) {
      if (response.data.is_bg_process) {
        setIsBgUnarchiving(true)
      }
    }
  }

  const checkMissingArchiveData = async () => {
    try {
      const response = await makeApiRequest('check-missing-archive-data', 'GET')
      console.log('check missing archive data', response)
      if (response.success && response.data) {
        setIsMissingArchiveData(response.data.is_missing)
        setIsGoogleDriveConnected(response.data.is_google_drive_connected)
      }
    } catch (error) {
      console.error('Error checking missing archive data:', error)
    }
  }

  const handleRecoverArchiveData = async () => {
    if (isRecoveringData) return

    setIsRecoveringData(true)
    try {
      const response = await makeApiRequest('recover-archive-data', 'POST')
      console.log('recover archive data response', response)

      if (response.success) {
        setIsMissingArchiveData(false)
        setShowSuccessNotice(true)
      } else {
        Siz.error(response.message || t('failed_to_recover_archive_data'), 4000)
      }
    } catch (error) {
      console.error('Error recovering archive data:', error)
      Siz.error(t('failed_to_recover_archive_data'), 4000)
    } finally {
      setIsRecoveringData(false)
    }
  }

  const handleCloseSuccessNotice = () => {
    setShowSuccessNotice(false)
  }

  const handleFlexOrderModalClose = async () => {
    setIsFlexOrderModalOpen(false)
    // Persist dismissal so it never shows again
    await makeApiRequest('flexorder-dismiss-modal', 'POST')
    if (window?.archm_admin?.flexorder_promo) {
      window.archm_admin.flexorder_promo.show_modal = false
    }
  }

  const handleFlexOrderBannerDismiss = async () => {
    setIsFlexOrderBannerOpen(false)
    // Persist dismissal
    await makeApiRequest('flexorder-dismiss-banner', 'POST')
    if (window?.archm_admin?.flexorder_promo) {
      window.archm_admin.flexorder_promo.show_banner = false
    }
  }

  const handleFlexOrderDashboardModalClose = async () => {
    setIsFlexOrderDashboardModalOpen(false)
    // Persist dismissal
    await makeApiRequest('flexorder-dismiss-dashboard-modal', 'POST')
    if (window?.archm_admin?.flexorder_promo) {
      window.archm_admin.flexorder_promo.show_dashboard_modal = false
    }
  }

  useEffect(() => {
    setIsPro(archm_admin.is_pro)
    setIsSqliteEnable(archm_admin.pdo_sqlite_enable)
    console.log('archm admin localiaze', archm_admin)
    console.log('ARCHM ADMIN:', AdminSettings)
    handleDashboardView()
    handleBackgorundArchiving()
    getSiteOrderInfo()
    checkBgUnnarchiving()
    checkMissingArchiveData()
    if (valueArchivedOrderPage) {
      handleViewChange(valueArchivedOrderPage)
    }

    // Initialize menu click handler
    initMenuClickHandler()

    // Cleanup on unmount
    return () => {
      cleanupMenuClickHandler()
    }
  }, [])

  useEffect(() => {
    if (archiving === 'archiving__start') {
      if (canceArchivelRef.current) {
        canceArchivelRef.current = false
      }
      setSettingOffTooltip(false)
      setArchivedOrders(0)
      setTotalArchiveOrders(0)
      setPercentage(0)
      fetchArchivingStatus()
      fetchRemoteArchivingStatus()
    }

    if (
      'archiving__complete' === archiving ||
      'archiving__cancel' === archiving
    ) {
      setLastArchviedate(new Date().toLocaleString('sv').replace(',', ''))
      getSiteOrderInfo()
      // Check for missing archive data after archiving operations
      setTimeout(() => checkMissingArchiveData(), 2000)

      // FlexOrder Cross-Promotion Trigger
      const promoData = window?.archm_admin?.flexorder_promo
      if ('archiving__complete' === archiving && promoData?.show_modal) {
        setFlexOrderActiveOrders(siteTotalOrder)
        // Delay slightly so background data syncs first
        setTimeout(() => setIsFlexOrderModalOpen(true), 1500)
      }
    }

    if ('archive__failed' === archiving) {
      handleArchiveFailedToggleModal()
    }
  }, [archiving])

  // On mounted, check if archive_master_auth is in the url.
  useEffect(() => {
    const archive_master_auth = new URLSearchParams(window.location.search).get(
      'archive_master_auth'
    )
    if (archive_master_auth) {
      handleViewChange('archive_settings')
    }

    // FlexOrder First-Archive Dashboard Auto-Trigger
    // If the user has archived for the first time elsewhere (Order List/Single Order),
    // we show the promo modal automatically on the dashboard.
    const promoData = window?.archm_admin?.flexorder_promo
    if (promoData?.show_modal_auto) {
      // Delay slightly to ensure UI is ready
      setTimeout(() => {
        setFlexOrderActiveOrders(siteTotalOrder)
        setIsFlexOrderModalOpen(true)
      }, 1000)
    }
  }, [])

  // Detect hash changes and reset to dashboard when Dashboard route is active
  useEffect(() => {
    const currentHash = location.hash || '#/'
    const isDashboardRoute = currentHash === '#/' || currentHash === ''
    
    // If we're on Dashboard route but not showing dashboard view, reset to dashboard
    if (isDashboardRoute && activeView !== 'dashboard_settings') {
      setActiveView('dashboard_settings')
      handleDashboardView()
    }
  }, [location.hash])

  // Listen for Dashboard menu clicks from WordPress admin menu
  useEffect(() => {
    const handleDashboardMenuClick = () => {
      // Reset to dashboard view when Dashboard menu is clicked
      if (activeView !== 'dashboard_settings') {
        setActiveView('dashboard_settings')
        handleDashboardView()
      }
    }

    const eventName = getDashboardClickEventName()
    document.addEventListener(eventName, handleDashboardMenuClick)

    return () => {
      document.removeEventListener(eventName, handleDashboardMenuClick)
    }
  }, [activeView])

  // Memoize chart data to prevent unnecessary re-renders
  // Only re-render when actual data values change
  const barChartData = useMemo(
    () => [siteArchivedOrder, siteTotalOrder],
    [siteArchivedOrder, siteTotalOrder]
  )

  // Static arrays - memoize to prevent new references on each render
  const barChartCategories = useMemo(() => [t('archived_database'), t('live_database')], [])
  const barChartColors = useMemo(() => ['#3A48E8', '#FF6B3A'], [])

  return (
    <>
      {'sqlite' === AdminSettings.selected_database && !isSqliteEnable && (
        <NoticeBar />
      )}
      {isMissingArchiveData && isGoogleDriveConnected && (
        <div className='arcm-missing-archive-notice arcm-mb-4 arcm-p-4 arcm-bg-white arcm-border arcm-rounded-lg'>
          <div className='arcm-gap-3 arcm-mb-3'>
            <div className='arcm-flex arcm-items-center arcm-mb-1'>
              <svg
                xmlns='http://www.w3.org/2000/svg'
                width='24'
                height='24'
                viewBox='0 0 24 24'
                fill='none'
              >
                <circle cx='12' cy='12' r='12' fill='#FCF4EC' />
                <path
                  d='M15.5007 7.625C15.5007 9.07487 13.1503 10.25 10.2503 10.25C7.3504 10.25 5 9.07487 5 7.625C5 6.17513 7.3504 5 10.2503 5C13.1503 5 15.5007 6.17513 15.5007 7.625ZM14.3544 10.264C14.4454 10.2185 14.5358 10.1701 14.6256 10.1188V10.3051C14.3827 10.3663 14.1559 10.4798 13.9613 10.6375C13.7666 10.7953 13.6087 10.9936 13.4985 11.2186L10.4402 17.341C10.3094 17.5992 10.2453 17.8861 10.2538 18.1754C10.2624 18.4648 10.3433 18.7474 10.4892 18.9974C10.4105 18.9991 10.3308 19 10.2503 19C7.3504 19 5 17.8249 5 16.375V9.48C5.33515 9.79675 5.73505 10.0584 6.14632 10.264C7.24189 10.8117 8.69449 11.125 10.2503 11.125C11.8062 11.125 13.2588 10.8117 14.3544 10.264ZM14.2782 11.6097L11.219 17.733C11.1521 17.8665 11.1205 18.0148 11.1272 18.164C11.1338 18.3131 11.1785 18.4581 11.257 18.585C11.3355 18.712 11.4452 18.8168 11.5756 18.8895C11.7061 18.9621 11.8529 19.0001 12.0022 19H18.1241C18.2734 19.0001 18.4202 18.9621 18.5507 18.8895C18.6811 18.8168 18.7908 18.712 18.8693 18.585C18.9478 18.4581 18.9925 18.3131 18.9991 18.164C19.0058 18.0148 18.9742 17.8665 18.9073 17.733L15.8446 11.6089C15.772 11.4633 15.6603 11.3408 15.5219 11.2552C15.3836 11.1695 15.2241 11.1242 15.0614 11.1242C14.8987 11.1242 14.7392 11.1695 14.6009 11.2552C14.4625 11.3408 14.3508 11.4641 14.2782 11.6097ZM15.4989 13.3073V15.934C15.4989 16.05 15.4528 16.1613 15.3708 16.2434C15.2887 16.3254 15.1774 16.3715 15.0614 16.3715C14.9454 16.3715 14.8341 16.3254 14.752 16.2434C14.67 16.1613 14.6239 16.05 14.6239 15.934V13.3073C14.6239 13.1912 14.67 13.0799 14.752 12.9979C14.8341 12.9158 14.9454 12.8698 15.0614 12.8698C15.1774 12.8698 15.2887 12.9158 15.3708 12.9979C15.4528 13.0799 15.4989 13.1912 15.4989 13.3073ZM15.0614 18.1232C14.9454 18.1232 14.8341 18.0772 14.752 17.9951C14.67 17.9131 14.6239 17.8018 14.6239 17.6857C14.6239 17.5697 14.67 17.4584 14.752 17.3764C14.8341 17.2943 14.9454 17.2483 15.0614 17.2483C15.1774 17.2483 15.2887 17.2943 15.3708 17.3764C15.4528 17.4584 15.4989 17.5697 15.4989 17.6857C15.4989 17.8018 15.4528 17.9131 15.3708 17.9951C15.2887 18.0772 15.1774 18.1232 15.0614 18.1232Z'
                  fill='#F9A444'
                />
              </svg>
              <h3 className='arcm-text-base arcm-text-black arcm-ml-1'>
                {t('missing_archived_data')}
              </h3>
            </div>
            <div className='arcm-flex-1'>
              <p className='arcm-text-base arcm-text-black'>
                {t('missing_archived_data_desc')}
              </p>
            </div>
          </div>
          <div className='arcm-w-full arcm-flex arcm-justify-end'>
            <button
              onClick={handleRecoverArchiveData}
              disabled={isRecoveringData}
              className='arcm-inline-flex arcm-items-center arcm-px-4 arcm-py-2 arcm-border arcm-border-transparent arcm-text-sm arcm-font-medium arcm-rounded-md arcm-text-white arcm-bg-blue-600 hover:arcm-bg-blue-700 focus:arcm-outline-none focus:arcm-ring-2 focus:arcm-ring-offset-2 focus:arcm-ring-blue-500 disabled:arcm-opacity-50 disabled:arcm-cursor-not-allowed arcm-transition-colors'
            >
              {isRecoveringData ? (
                <>
                  <svg
                    className='arcm-animate-spin arcm--ml-1 arcm-mr-2 arcm-h-4 arcm-w-4 arcm-text-white'
                    xmlns='http://www.w3.org/2000/svg'
                    fill='none'
                    viewBox='0 0 24 24'
                  >
                    <circle
                      className='arcm-opacity-25'
                      cx='12'
                      cy='12'
                      r='10'
                      stroke='currentColor'
                      strokeWidth='4'
                    ></circle>
                    <path
                      className='arcm-opacity-75'
                      fill='currentColor'
                      d='M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z'
                    ></path>
                  </svg>
                  {t('recovering')}
                </>
              ) : (
                t('recover_archive_data')
              )}
            </button>
          </div>
        </div>
      )}
      {showSuccessNotice && (
        <div className='arcm-success-notice arcm-mb-4 arcm-p-4 arcm-bg-white arcm-border arcm-border-green-200 arcm-rounded-lg'>
          <div className='arcm-flex arcm-items-center arcm-gap-2 arcm-mb-2'>
            <div className='arcm-flex-shrink-0'>
              <svg
                width='20'
                height='20'
                viewBox='0 0 20 20'
                fill='none'
                xmlns='http://www.w3.org/2000/svg'
              >
                <circle
                  cx='10'
                  cy='10'
                  r='9'
                  fill='white'
                  stroke='#10B981'
                  strokeWidth='2'
                />
                <path
                  d='M7.5 10L9 11.5L12.5 8'
                  stroke='#10B981'
                  strokeWidth='2'
                  strokeLinecap='round'
                  strokeLinejoin='round'
                />
              </svg>
            </div>
            <h4 className='arcm-text-sm arcm-font-medium arcm-text-gray-900'>
              {t('archived_data_recovered_successfully')}
            </h4>
          </div>
          <p className='arcm-text-sm arcm-text-gray-600 arcm-ml-6 arcm-mb-3'>
            {t('archived_data_restored_successfully')}
          </p>
          <div className='arcm-flex arcm-justify-end'>
            <button
              onClick={handleCloseSuccessNotice}
              className='arcm-px-3 arcm-py-1 arcm-text-sm arcm-text-blue-600 arcm-bg-white arcm-border arcm-border-blue-600 arcm-rounded arcm-hover:arcm-bg-blue-50 arcm-transition-colors'
            >
              {t('close')}
            </button>
          </div>
        </div>
      )}
      <div className='wooarchive-settings'>
        {activeView === 'dashboard_settings' ? (
          initialLoading ? (
            <div class='dashboard-loader arcm-w-full arcm-min-h-[500px] sm:arcm-min-h-[600px] arcm-flex arcm-justify-center arcm-items-center'>
              {arcmIcons.SpinningAnimation}
            </div>
          ) : (
            <>
              {!isOnboardingComplete && onBoardingLoad ? (
                <Onboarding
                  totalOrderToArchive={totalOrderToArchive}
                  totalOrder={totalOrder}
                  olderSchedule={olderSchedule}
                  onvVeiwChange={handleViewChange}
                  setTotalOrderToArchive={setTotalOrderToArchive}
                />
              ) : (
                // <ActiveWooCommerce />
                <>
                  <div className='wooarchive-settings__dashboard'>
                    <div className='header arcm-flex-wrap arcm-flex arcm-items-center arcm-justify-between arcm-gap-2 arcm-mb-4'>
                      <h4 className='arcm-text-gray-800 arcm-text-lg sm:arcm-text-xl arcm-font-bold'>
                        {t('dashboard')}
                      </h4>

                      <div className='arcm-inline-flex arcm-flex-wrap arcm-items-center arcm-gap-x-4 !arcm-gap-y-2.5 sm:arcm-gap-8 arcm-ml-auto'>
                        <button
                          onClick={() => handleViewChange('dashboard_settings')}
                          className={`arcm-text-xs sm:arcm-text-sm arcm-font-medium arcm-inline-flex arcm-items-center arcm-gap-1 arcm-group arcm-transition-all hover:arcm-text-[#3858e9] ${
                            activeView === 'dashboard_settings'
                              ? 'arcm-text-[#3858e9] active'
                              : 'arcm-text-gray-800'
                          }`}
                        >
                          <span className='icon'>{arcmIcons.dashboard}</span>
                          {t('dashboard')}
                        </button>
                        <div
                          onMouseEnter={() => setSettingOffTooltip(true)}
                          onMouseLeave={() => setSettingOffTooltip(false)}
                          className='arcm-relative arcm-inline-block'
                        >
                          <button
                            onClick={() =>
                              archiving === 'archiving__start' ||
                              isBgUnarchiving
                                ? null
                                : handleViewChange('archive_settings')
                            }
                            disabled={
                              archiving === 'archiving__start' ||
                              isBgUnarchiving
                            }
                            className={`arcm-text-xs sm:arcm-text-sm arcm-font-medium arcm-inline-flex arcm-items-center arcm-gap-1 arcm-group arcm-transition-all hover:arcm-text-[#3858e9] ${
                              archiving === 'archiving__start' ||
                              isBgUnarchiving
                                ? 'arcm-text-[#3858e9] active'
                                : 'arcm-text-gray-800'
                            } ${
                              archiving === 'archiving__start' ||
                              isBgUnarchiving
                                ? 'arcm-opacity-50 arcm-cursor-not-allowed'
                                : ''
                            }`}
                          >
                            <span className='icon'>{arcmIcons.settings}</span>
                            {t('archive_settings')}
                          </button>

                          {(archiving === 'archiving__start' ||
                            isBgUnarchiving) &&
                            settingOffTooltip && (
                              <div className='arcm-absolute arcm-left-1/2 arcm-transform arcm--translate-x-1 arcm-whitespace-nowrap arcm-mt-2 arcm-px-3 arcm-py-2 arcm-bg-white arcm-border arcm-border-gray-200 arcm-rounded-lg arcm-shadow-lg arcm-z-50'>
                                {archiving === 'archiving__start' && (
                                  <div className='arcm-text-sm arcm-text-gray-600'>
                                    {t('settings_access_disabled_archiving')}
                                  </div>
                                )}

                                {isBgUnarchiving && (
                                  <div className='arcm-text-sm arcm-text-gray-600'>
                                    The Archive Settings can’t be accessed
                                    during unarchiving.
                                    <br /> Go to Archived Orders page to see the
                                    orders unarchiving progress
                                  </div>
                                )}

                                {archiving === 'archiving__start' &&
                                  isBgUnarchiving && (
                                    <div className='arcm-text-sm arcm-text-gray-600'>
                                      {t('settings_access_disabled_archiving')}
                                    </div>
                                  )}

                                {/* Arrow */}
                                <div className='arcm-absolute arcm-top-0 arcm-left-1/2 arcm-transform arcm--translate-x-1/2 arcm--translate-y-1/2 arcm-rotate-45 arcm-w-2 arcm-h-2 arcm-bg-white arcm-border-t arcm-border-l arcm-border-gray-200'></div>
                              </div>
                            )}
                        </div>
                        <Link
                          to='archived-order'
                          className={`arcm-text-xs sm:arcm-text-sm arcm-font-medium arcm-inline-flex arcm-items-center arcm-gap-1 arcm-group arcm-transition-all hover:arcm-text-[#3858e9] ${({
                            isActive
                          }) =>
                            isActive
                              ? 'arcm-text-[#3858e9] active'
                              : 'arcm-text-gray-800'} `}
                        >
                          <span className='icon'>
                            {arcmIcons.archiveOrders}
                          </span>
                          {t('archived_orders')}
                        </Link>
                        <button
                          onClick={() => handleViewChange('export_orders')}
                          className={`arcm-text-xs sm:arcm-text-sm arcm-font-medium arcm-inline-flex arcm-items-center arcm-gap-1 arcm-group arcm-transition-all hover:arcm-text-[#3858e9] ${
                            activeView === 'export_orders'
                              ? 'arcm-text-[#3858e9] active'
                              : 'arcm-text-gray-800'
                          }`}
                        >
                          <span className='icon'>{arcmIcons.exportOrders}</span>
                          {t('export_data')}
                        </button>
                        <Link
                          to='logs'
                          className={`arcm-text-xs sm:arcm-text-sm arcm-font-medium arcm-inline-flex arcm-items-center arcm-gap-1 arcm-group arcm-transition-all hover:arcm-text-[#3858e9] ${
                            activeView === 'archiving_log'
                              ? 'arcm-text-[#3858e9] active'
                              : 'arcm-text-gray-800'
                          }`}
                          type='button'
                        >
                          <span className='icon'>{arcmIcons.logs}</span>
                          {t('log')}
                        </Link>
                        {!isPro && (
                          <button
                            onClick={redirectProPage}
                            className='arcm-btn-bounce arcm-text-xs sm:arcm-text-sm arcm-text-[#A34AE8] arcm-font-medium arcm-inline-flex arcm-items-center arcm-gap-1'
                          >
                            <span className='icon arcm-inline-block'>
                              {arcmIcons.upgrade}
                            </span>
                            {t('upgrade_now')}
                          </button>
                        )}
                      </div>
                    </div>

                    <div className='ready-archive  arcm-mb-4 arcm-px-5 arcm-py-6 sm:arcm-px-8 sm:arcm-py-10 md:arcm-px-10 md:arcm-py-12 arcm-bg-white arcm-rounded-lg arcm-border arcm-border-gray-200'>
                      {archiving === false ||
                      archiving === 'archive__failed' ||
                      archiving === 'archiving__cancel' ||
                      archiving === 'archiving__complete' ? (
                        <div className='arcm-flex arcm-flex-col arcm-gap-y-6 md:arcm-flex-row arcm-items-center arcm-justify-start'>
                          {archiving === 'archiving__cancel' ||
                          archiving === 'archiving__complete' ||
                          (lastArchiveDate && 0 === totalOrderToArchive) ? (
                            <div className='arcm-last-order-archived arcm-text-center arcm-min-w-[315px] md:arcm-min-w-[345px]'>
                              <div className='icon arcm-mb-4'>
                                <svg
                                  className='arcm-ml-auto arcm-mr-auto'
                                  xmlns='http://www.w3.org/2000/svg'
                                  width='89'
                                  height='89'
                                  viewBox='0 0 89 89'
                                  fill='none'
                                >
                                  <g clip-path='url(#clip0_634_2794)'>
                                    <path
                                      d='M29.1679 0.5C26.4376 0.5 24.5098 3.17479 25.3731 5.76491L26.4353 8.95135C26.9797 10.5847 28.5083 11.6864 30.23 11.6864H44.1702C46.9004 11.6864 48.8283 9.01165 47.9649 6.42153L46.9027 3.23509C46.3583 1.60172 44.8297 0.5 43.108 0.5H29.1679Z'
                                      fill='#6DEDD4'
                                    />
                                    <path
                                      d='M77.1667 7.83333C79.3758 7.83333 81.1667 9.6242 81.1667 11.8333V62.5C81.1667 64.7091 79.3758 66.5 77.1667 66.5H4.49999C2.29086 66.5 0.5 64.7091 0.5 62.5V4.5C0.5 2.29086 2.29086 0.5 4.5 0.5H27.3612C28.8763 0.5 30.2613 1.35601 30.9389 2.71115L32.3944 5.62219C33.072 6.97732 34.457 7.83333 35.9721 7.83333H77.1667Z'
                                      fill='#468FF1'
                                    />
                                    <path
                                      d='M5.22184 66.5C2.75008 66.5 0.869911 64.2805 1.27627 61.8424L7.27627 25.8424C7.59773 23.9136 9.26649 22.5 11.2218 22.5H83.7782C86.2499 22.5 88.1301 24.7195 87.7237 27.1576L81.7237 63.1576C81.4023 65.0863 79.7335 66.5 77.7782 66.5H5.22184Z'
                                      fill='#61C5FA'
                                    />
                                    <path
                                      d='M44.4997 88.4998C58.675 88.4998 70.1663 77.0085 70.1663 62.8332C70.1663 48.6579 58.675 37.1665 44.4997 37.1665C30.3244 37.1665 18.833 48.6579 18.833 62.8332C18.833 77.0085 30.3244 88.4998 44.4997 88.4998Z'
                                      fill='#6DEDD4'
                                    />
                                    <path
                                      d='M40.8329 75.3514L30.9072 65.4257L36.0919 60.241L40.8329 64.982L52.9072 52.9077L58.0919 58.0924L40.8329 75.3514Z'
                                      fill='white'
                                    />
                                  </g>
                                  <defs>
                                    <clipPath id='clip0_634_2794'>
                                      <rect
                                        x='0.5'
                                        y='0.5'
                                        width='88'
                                        height='88'
                                        rx='8'
                                        fill='white'
                                      />
                                    </clipPath>
                                  </defs>
                                </svg>
                              </div>

                              <div className='text'>
                                <div className='arcm-text-gray-800 arcm-text-base arcm-font-semibold arcm-mb-1.5'>
                                  {t('orders_archived')}
                                </div>
                                <div className='arcm-text-gray-600 arcm-text-xs arcm-font-normal arcm-mb-4'>
                                  {t('older_than')}{' '}
                                  {'default' !== AdminSettings.archive_range
                                    ? AdminSettings.archive_range === 'custom_date' && AdminSettings.archive_range_datetime
                                      ? AdminSettings.archive_range_datetime
                                      : t(`archive_range_options.${AdminSettings.archive_range}`) || AdminSettings.archive_range.replace('_', ' ')
                                    : ''}
                                </div>
                                <div className='arcm-text-gray-900 arcm-text-sm arcm-font-normal'>
                                  <span class='arcm-font-semibold'>
                                    {t('last_archived_on')}
                                  </span>{' '}
                                  {formateLastArchivedDate(lastArchiveDate)}
                                </div>
                              </div>
                            </div>
                          ) : (
                            <div className='chart-wrap arcm-text-center arcm-min-w-[315px] md:arcm-min-w-[345px]'>
                              <PieChart
                                className='arcm-h-[173px] arcm-w-[173px] arcm-mb-1.5 arcm-ml-auto arcm-mr-auto'
                                value={totalOrderToArchive} // Percentage value
                                remainingValue={totalOrder}
                                color='#F7416E' // Custom color for the filled part
                              />
                              <div className='arcm-text-gray-800 arcm-text-base arcm-font-bold arcm-mb-1.5 arcm-ml-auto arcm-mr-auto'>
                                <span className='arcm-text-[#f6406e]'>
                                  {totalOrderToArchive} {t('order')}
                                </span>{' '}
                                {t('can_be_archived')}
                              </div>
                              <div className='arcm-text-gray-600 arcm-text-xs arcm-font-normal arcm-ml-auto arcm-mr-auto'>
                                {t('older_than')}{' '}
                                {'default' !== AdminSettings.archive_range
                                  ? AdminSettings.archive_range ===
                                    'custom_date'
                                    ? AdminSettings.archive_range_datetime
                                    : t(`archive_range_options.${AdminSettings.archive_range}`) || AdminSettings.archive_range.replace('_', ' ')
                                  : ''}
                              </div>
                            </div>
                          )}
                          <hr className='arcm-w-[1px] arcm-h-[200px] arcm-mx-8 arcm-border-none arcm-bg-gray-200 arcm-hidden md:arcm-inline' />
                          <div className='text-wrap arcm-text-center md:arcm-text-left'>
                            <div className='arcm-text-gray-800 arcm-text-lg sm:arcm-text-xl arcm-font-bold arcm-mb-1.5'>
                              {t('archive_orders_now')}
                            </div>
                            <div className='arcm-text-gray-900 arcm-text-sm arcm-font-normal arcm-mb-4'>
                              {t('archive_old_orders_desc')}
                            </div>
                            <button
                              onClick={handleToggleModal}
                              className='arcm-text-white arcm-text-xs sm:arcm-text-sm arcm-font-semibold arcm-min-w-[160px] arcm-px-4 arcm-py-2.5 arcm-bg-[#3858e9] arcm-rounded-lg arcm-justify-center arcm-items-center arcm-gap-2 arcm-inline-flex arcm-transition-all hover:arcm-bg-blue-700'
                            >
                              <span>{t('archive_now')}</span>
                              <span>
                                <svg
                                  xmlns='http://www.w3.org/2000/svg'
                                  width='18'
                                  height='15'
                                  viewBox='0 0 18 15'
                                  fill='none'
                                >
                                  <path
                                    d='M10.25 1.25L16.5 7.5M16.5 7.5L10.25 13.75M16.5 7.5H1.5'
                                    stroke='white'
                                    stroke-width='1.5'
                                    stroke-linecap='round'
                                    stroke-linejoin='round'
                                  />
                                </svg>
                              </span>
                            </button>
                          </div>
                        </div>
                      ) : (
                        ''
                      )}

                      {archiving === 'archiving__start' ? (
                        <>
                          <div className='arcm-text-gray-800 arcm-text-lg sm:arcm-text-xl arcm-font-bold arcm-mb-1.5'>
                            {archiving === 'archiving__start' &&
                              t('archiving_order')}
                            ({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 class='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={() =>
                                setIsArchiveCancel(!isArchiveCancel)
                              }
                              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', t('archiving'))}
                          </div>
                        </>
                      ) : (
                        ''
                      )}
                    </div>

                    {isFlexOrderBannerOpen && (
                      <FlexOrderPromoBanner 
                        activeOrders={siteTotalOrder}
                        onDismiss={handleFlexOrderBannerDismiss}
                      />
                    )}

                    <FlexOrderPromoModal 
                      isOpen={isFlexOrderDashboardModalOpen}
                      onClose={handleFlexOrderDashboardModalClose}
                      activeOrders={window?.archm_admin?.flexorder_promo?.active_orders || 0}
                      variant="dashboard"
                    />

                    <div className='ready-archive arcm-flex arcm-flex-col arcm-gap-y-6 xl:arcm-flex-row xl:arcm-items-center arcm-justify-between arcm-px-5 arcm-py-6 sm:arcm-px-8 sm:arcm-py-10 md:arcm-px-10 md:arcm-py-12 arcm-bg-white arcm-rounded-lg arcm-border arcm-border-gray-200'>
                      <div className='chart-wrap'>
                        <BarChart
                          data={barChartData}
                          categories={barChartCategories}
                          colors={barChartColors}
                          className='arcm-h-[160px] arcm-w-[370px] arcm-bg-gray-50 arcm-rounded-lg'
                        />
                        <div className=' arcm-flex arcm-flex-row arcm-items-center arcm-gap-y-3 arcm-mt-4'>
                          <div className='label-item'>
                            <div className='icon-wrap arcm-inline-flex arcm-items-center arcm-gap-x-1 arcm-mb-1'>
                              <div className='icon arcm-flex arcm-justify-center arcm-items-center arcm-w-[29px] arcm-h-[29px] arcm-rounded-full arcm-bg-[#EEF2FF]'>
                                <svg
                                  xmlns='http://www.w3.org/2000/svg'
                                  width='16'
                                  height='19'
                                  viewBox='0 0 16 19'
                                  fill='none'
                                >
                                  <path
                                    d='M10.1982 18.4694C10.5612 18.3915 10.9119 18.1186 11.0796 17.7836C11.1269 17.6889 11.1657 17.5987 11.1657 17.583C11.1657 17.5589 11.4771 17.5545 13.1728 17.5545H15.1799V17.1737V16.7928L13.1779 16.7921L11.176 16.7914L11.0865 16.6036C10.9658 16.3502 10.7595 16.1394 10.5096 16.0144C10.415 15.967 10.3247 15.9282 10.309 15.9282C10.2852 15.9282 10.2805 15.7759 10.2805 14.994V14.0597L10.3268 14.0473C10.3523 14.0405 10.438 14.0348 10.5173 14.0346C10.6805 14.034 11.2781 13.9678 11.5259 13.9225C11.8742 13.8588 11.9458 13.8434 12.2113 13.7756C13.3492 13.4849 14.2811 12.9684 14.7528 12.3669C14.8105 12.2933 14.8702 12.2227 14.8854 12.21C14.9269 12.1752 15.0679 11.9513 15.1274 11.8255L15.1799 11.7145V10.1777C15.1799 9.3325 15.1729 8.64107 15.1644 8.64122C15.1559 8.64122 15.1119 8.73328 15.0666 8.84547C15.0214 8.95766 14.9704 9.07132 14.9534 9.09803C14.9364 9.12475 14.9133 9.16153 14.902 9.17978C14.7071 9.49381 14.4051 9.76268 13.9301 10.0451C13.8484 10.0937 13.7789 10.1382 13.7757 10.1442C13.7632 10.167 13.2851 10.3904 13.0596 10.4789C12.7866 10.5859 12.5889 10.6513 12.2979 10.7306C12.039 10.8012 11.9149 10.8279 11.5157 10.8985C10.9759 10.9941 10.3676 11.0374 9.72368 11.0262L9.23888 11.0177L9.23614 11.5019C9.23322 12.0122 9.21332 12.2007 9.11776 12.6218C9.03098 13.0042 8.84364 13.4904 8.63741 13.8684C8.61114 13.9166 8.59311 13.9594 8.59733 13.9637C8.60791 13.9742 9.2094 14.0335 9.37913 14.0406C9.45512 14.0439 9.52228 14.0515 9.52838 14.0576C9.53447 14.0637 9.5393 14.4847 9.53911 14.9933L9.53852 15.9179L9.42433 15.9621C9.2487 16.03 9.13081 16.1102 8.969 16.2718C8.8517 16.3889 8.80231 16.4585 8.73227 16.6056L8.64377 16.7914L6.64182 16.7921L4.63989 16.7928V17.1737V17.5545L6.64182 17.5551L8.64377 17.5557L8.68794 17.6699C8.75577 17.8452 8.836 17.9633 8.99637 18.124C9.3056 18.4338 9.75878 18.5642 10.198 18.4699L10.1982 18.4694ZM4.96947 15.5559C5.25524 15.5115 5.4528 15.4649 5.70207 15.3831C6.98775 14.9608 7.97398 13.8946 8.30139 12.5728C8.44568 11.9903 8.44568 11.2615 8.30139 10.679C7.91313 9.11155 6.62215 7.94286 5.01593 7.70473C4.74001 7.66383 4.16967 7.66383 3.89375 7.70473C2.14263 7.96435 0.793303 9.31367 0.533692 11.0648C0.468682 11.5033 0.49995 12.1354 0.608294 12.5728C0.996548 14.1402 2.28753 15.3089 3.89375 15.547C4.12337 15.5811 4.77285 15.5864 4.96947 15.5559ZM2.78739 13.9623L1.89207 13.0668L2.7926 12.1663L3.69313 11.2657L4.03779 11.6104L4.38245 11.9551L4.08512 12.2529C3.92159 12.4167 3.79507 12.5581 3.80396 12.5669C3.81285 12.5758 4.52569 12.5847 5.38805 12.5866C6.25041 12.5885 6.96756 12.5908 6.98171 12.5917C7.0015 12.593 7.00744 12.7027 7.00744 13.0669C7.00744 13.3273 7.00049 13.5412 6.992 13.5423C6.98351 13.5434 6.26636 13.5457 5.39834 13.5474C4.53032 13.5492 3.81285 13.5579 3.80396 13.5668C3.79507 13.5757 3.92155 13.7169 4.08504 13.8807L4.38229 14.1785L4.04311 14.5181C3.85657 14.7049 3.69917 14.8578 3.69333 14.8578C3.68749 14.8578 3.27981 14.4548 2.78739 13.9623ZM4.84598 11.6156L4.50681 11.276L4.80406 10.9782C4.96754 10.8144 5.09427 10.6734 5.08567 10.6648C5.07707 10.6562 4.3596 10.6489 3.49129 10.6486L1.91253 10.648V10.1643V9.68051L3.50276 9.67526C4.37739 9.67234 5.09299 9.66321 5.09299 9.65493C5.09299 9.64665 4.96106 9.50772 4.79982 9.34618L4.50664 9.05248L4.8513 8.70783L5.19597 8.36317L6.09649 9.2637L6.99703 10.1642L6.10171 11.0597C5.60928 11.5523 5.20161 11.9552 5.19577 11.9552C5.18993 11.9552 5.03253 11.8024 4.84598 11.6156ZM10.3011 10.0492C10.3521 10.0448 10.5327 10.0314 10.7025 10.0194C11.3609 9.97315 12.1005 9.82888 12.7076 9.62829C13.4869 9.37084 14.1237 9.00976 14.5563 8.58007C14.7061 8.43118 14.8942 8.19537 14.9659 8.06652C14.9873 8.02795 15.0419 7.93069 15.0872 7.85038L15.1696 7.70436L15.1752 6.17588C15.1783 5.33522 15.1737 4.64745 15.1649 4.64749C15.1562 4.64753 15.1318 4.69154 15.1107 4.74527C14.9138 5.24822 14.6744 5.53823 14.1635 5.89283C14.0656 5.96076 13.9601 6.03055 13.9291 6.04791C13.8981 6.06527 13.8356 6.10277 13.7904 6.13125C13.7451 6.15973 13.6154 6.22779 13.5022 6.28248C13.2312 6.41341 13.1983 6.42786 13.0287 6.49066C12.9494 6.52 12.8522 6.55651 12.8126 6.57179C12.3604 6.74609 11.4911 6.9287 10.8055 6.99343C10.5126 7.02108 9.30744 7.02108 9.01453 6.99343C8.32889 6.9287 7.45964 6.74609 7.00745 6.57179C6.96782 6.55651 6.87056 6.52 6.7913 6.49066C6.62248 6.42814 6.59415 6.41562 6.30342 6.27486C6.18227 6.21621 6.04985 6.14563 6.00916 6.11802C5.96846 6.0904 5.93045 6.06781 5.92468 6.06781C5.91029 6.06781 5.48851 5.77986 5.41208 5.71786C5.2804 5.61105 5.03109 5.34507 4.95536 5.23062C4.87264 5.1056 4.77476 4.91259 4.70925 4.74527C4.68821 4.69154 4.66405 4.64753 4.65556 4.64749C4.64706 4.64745 4.64012 5.13663 4.64012 5.73455V6.82169L4.97462 6.84631C6.10555 6.92953 7.0975 7.38414 7.88432 8.17981C8.3368 8.63739 8.71463 9.2298 8.94134 9.83715L9.00748 10.0143L9.18598 10.0279C9.41361 10.0452 10.1794 10.0598 10.3011 10.0492ZM10.4452 6.01448C10.4962 6.01017 10.6583 5.99634 10.8055 5.98379C12.4203 5.84611 13.8909 5.26947 14.629 4.4845C16.0824 2.93882 14.5318 1.08821 11.3763 0.602623C10.8249 0.517772 10.5693 0.5 9.8997 0.5C9.23014 0.5 8.97448 0.517772 8.42309 0.602623C6.36313 0.919629 4.88159 1.84724 4.65213 2.96368C4.3821 4.27761 5.93372 5.51131 8.34878 5.90289C8.83379 5.98153 9.16987 6.0082 9.76589 6.01533C10.0886 6.01918 10.3943 6.0188 10.4452 6.01448Z'
                                    fill='#4F46E5'
                                  />
                                </svg>
                              </div>
                              <div className='arcm-text-indigo-600 arcm-text-lg arcm-font-bold'>
                                {siteArchivedOrder}
                              </div>
                            </div>
                            <div className='arcm-text-gray-800 arcm-text-xs arcm-font-normal'>
                              {t('orders_in_archived_db')}
                            </div>
                          </div>
                          <hr className='arcm-w-[1px] arcm-h-[43px] arcm-mx-6 arcm-border-none arcm-bg-[#D1D5DB]' />
                          <div className='label-item'>
                            <div className='icon-wrap arcm-inline-flex arcm-items-center arcm-gap-x-1 arcm-mb-1'>
                              <div className='icon arcm-flex arcm-justify-center arcm-items-center arcm-w-[29px] arcm-h-[29px] arcm-rounded-full arcm-bg-orange-50'>
                                <svg
                                  xmlns='http://www.w3.org/2000/svg'
                                  width='14'
                                  height='14'
                                  viewBox='0 0 14 14'
                                  fill='none'
                                >
                                  <path
                                    d='M13.5 1.75C13.5 0.783463 10.5899 0 7.00006 0C3.41018 0 0.5 0.783463 0.5 1.75C0.5 2.71654 3.41018 3.5 7.00006 3.5C10.5899 3.5 13.5 2.71654 13.5 1.75Z'
                                    fill='#BDDBFF'
                                  />
                                  <path
                                    d='M7.00006 7C10.5885 7 13.5 6.2175 13.5 5.25V1.75C13.5 2.7175 10.5885 3.5 7.00006 3.5C3.41145 3.5 0.5 2.7175 0.5 1.75V5.25C0.5 6.2175 3.41145 7 7.00006 7Z'
                                    fill='#9BC9FF'
                                  />
                                  <path
                                    d='M7.00006 10.5C10.5885 10.5 13.5 9.7175 13.5 8.75V5.25C13.5 6.2175 10.5885 7 7.00006 7C3.41145 7 0.5 6.2175 0.5 5.25V8.75C0.5 9.7175 3.41145 10.5 7.00006 10.5Z'
                                    fill='#57A4FF'
                                  />
                                  <path
                                    d='M13.5 8.75C13.5 9.7175 10.5885 10.5 7.00006 10.5C3.41145 10.5 0.5 9.7175 0.5 8.75V12.25C0.5 13.2175 3.41145 14 7.00006 14C10.5885 14 13.5 13.2175 13.5 12.25V8.75Z'
                                    fill='#2488FF'
                                  />
                                </svg>
                              </div>
                              <div className='arcm-text-orange-500 arcm-text-lg arcm-font-bold'>
                                {siteTotalOrder}
                              </div>
                            </div>
                            <div className='arcm-text-gray-800 arcm-text-xs arcm-font-normal'>
                              {t('orders_in_live_db')}
                            </div>
                          </div>
                        </div>
                      </div>
                      <hr className='arcm-w-[1px] arcm-h-[200px] arcm-mx-8 arcm-border-none arcm-bg-gray-200 arcm-hidden xl:arcm-inline' />
                      <div className='text-wrap'>
                        <div className='arcm-flex arcm-justify-between arcm-items-center arcm-mb-4'>
                          <div className='arcm-text-gray-800 arcm-text-lg sm:arcm-text-xl arcm-font-bold'>
                            {t('archive_options_overview')}
                          </div>
                          <button
                            onClick={() => handleViewChange('archive_settings')}
                            className='arcm-text-xs sm:arcm-text-sm arcm-font-medium arcm-inline-flex arcm-items-center arcm-gap-1 arcm-group arcm-transition-all arcm-text-[#3858e9]'
                          >
                            <span>
                              <svg
                                xmlns='http://www.w3.org/2000/svg'
                                width='20'
                                height='20'
                                viewBox='0 0 20 20'
                                fill='none'
                              >
                                <path
                                  className=' arcm-transition-all group-[.active]:arcm-stroke-[#3858e9] arcm-stroke-[#3858e9]'
                                  d='M7.99464 3.2835C8.06998 2.83145 8.46109 2.50012 8.91938 2.50012H11.081C11.5393 2.50012 11.9304 2.83145 12.0058 3.2835L12.1837 4.35104C12.2356 4.66274 12.4439 4.92238 12.7204 5.07542C12.7822 5.10964 12.8433 5.14498 12.9037 5.18143C13.1746 5.34499 13.504 5.39584 13.8003 5.28484L14.8144 4.90494C15.2435 4.74416 15.726 4.91721 15.9552 5.3141L17.036 7.18613C17.2651 7.58302 17.1737 8.0874 16.8199 8.37867L15.983 9.06769C15.7392 9.26835 15.6184 9.57822 15.6242 9.8939C15.6249 9.92923 15.6252 9.96464 15.6252 10.0001C15.6252 10.0356 15.6249 10.071 15.6242 10.1063C15.6184 10.422 15.7392 10.7319 15.983 10.9325L16.8199 11.6216C17.1737 11.9128 17.2651 12.4172 17.036 12.8141L15.9552 14.6861C15.726 15.083 15.2435 15.2561 14.8144 15.0953L13.8003 14.7154C13.504 14.6044 13.1746 14.6552 12.9037 14.8188C12.8433 14.8553 12.7822 14.8906 12.7204 14.9248C12.4439 15.0779 12.2356 15.3375 12.1837 15.6492L12.0058 16.7167C11.9304 17.1688 11.5393 17.5001 11.081 17.5001H8.91938C8.46109 17.5001 8.06998 17.1688 7.99464 16.7167L7.81671 15.6492C7.76476 15.3375 7.55645 15.0779 7.27998 14.9248C7.21817 14.8906 7.15707 14.8553 7.09671 14.8188C6.82585 14.6553 6.4964 14.6044 6.2001 14.7154L5.18604 15.0953C4.75688 15.2561 4.27439 15.083 4.04525 14.6861L2.96443 12.8141C2.73529 12.4172 2.82666 11.9128 3.18048 11.6216L4.01744 10.9326C4.2612 10.7319 4.38203 10.422 4.37618 10.1063C4.37553 10.071 4.3752 10.0356 4.3752 10.0001C4.3752 9.96464 4.37553 9.92923 4.37618 9.89391C4.38203 9.57823 4.2612 9.26837 4.01744 9.0677L3.18048 8.37868C2.82666 8.08741 2.73529 7.58303 2.96443 7.18614L4.04525 5.31411C4.27439 4.91722 4.75688 4.74417 5.18604 4.90495L6.20009 5.28484C6.49639 5.39585 6.82583 5.345 7.0967 5.18144C7.15706 5.14499 7.21816 5.10964 7.27998 5.07542C7.55645 4.92238 7.76476 4.66274 7.81671 4.35104L7.99464 3.2835Z'
                                  stroke='#3858e9'
                                  stroke-width='1.5'
                                  stroke-linecap='round'
                                  stroke-linejoin='round'
                                />
                                <path
                                  className=' arcm-transition-all group-[.active]:arcm-stroke-[#3858e9] arcm-stroke-[#3858e9]'
                                  d='M12.5 10.0001C12.5 11.3808 11.3807 12.5001 10 12.5001C8.61929 12.5001 7.50001 11.3808 7.50001 10.0001C7.50001 8.61934 8.61929 7.50006 10 7.50006C11.3807 7.50006 12.5 8.61934 12.5 10.0001Z'
                                  stroke='#3858e9'
                                  stroke-width='1.5'
                                  stroke-linecap='round'
                                  stroke-linejoin='round'
                                />
                              </svg>
                            </span>
                            {t('change')}
                          </button>
                        </div>
                        <table className='arcm-w-full arcm-max-w-[523px]'>
                          <tbody>
                            <tr>
                              <td className='arcm-border-0 arcm-text-gray-700 arcm-text-sm arcm-font-semibold arcm-leading-none arcm-py-2'>
                                <div className=' arcm-inline-flex arcm-items-center arcm-gap-2'>
                                  <span className='icon'>
                                    {arcmIcons.archive}
                                  </span>{' '}
                                  {t('archive_status')}
                                </div>
                              </td>
                              <td className='arcm-border-0 arcm-text-gray-900 arcm-text-sm arcm-font-nomal arcm-text-right arcm-leading-none arcm-py-2'>
                                {!AdminSettings.selected_database ? (
                                  <div className='arcm-inline-flex arcm-items-center arcm-gap-2 arcm-text-red-700'>
                                    <span className='icon'>
                                      {arcmIcons.alert}
                                    </span>{' '}
                                    {t('archive_options_not_configured')}
                                  </div>
                                ) : AdminSettings.selected_database === 'rds' &&
                                  !awsConnection ? (
                                  <div className='arcm-inline-flex arcm-items-center arcm-gap-2 arcm-text-red-700'>
                                    <span className='icon'>
                                      {arcmIcons.alert}
                                    </span>{' '}
                                    {t('rds_not_configured_short')}
                                  </div>
                                ) : AdminSettings.selected_database ===
                                    'google_drive' &&
                                  !googleDriveConnection.user_email ? (
                                  <div className='arcm-inline-flex arcm-items-center arcm-gap-2 arcm-text-red-700'>
                                    <span className='icon'>
                                      {arcmIcons.alert}
                                    </span>{' '}
                                    {t('google_drive_not_connected')}
                                  </div>
                                ) : (
                                  <div className='arcm-inline-flex arcm-items-center arcm-gap-2'>
                                    <span className='icon'>
                                      {arcmIcons.checkCircle}
                                    </span>
                                    {archiving === false &&
                                      t('ready_to_archive')}
                                    {archiving === 'archiving__start' && (
                                      <>
                                        <p>{t('status.archiving')}</p>
                                      </>
                                    )}
                                    {archiving === 'archiving__complete' &&
                                      t('status.archive_complete')}
                                  </div>
                                )}
                              </td>
                            </tr>
                            <tr>
                              <td className='arcm-border-0 arcm-text-gray-700 arcm-text-sm arcm-font-semibold arcm-leading-none arcm-py-2'>
                                <div className=' arcm-inline-flex arcm-items-center arcm-gap-2'>
                                  <span className='icon'>
                                    {arcmIcons.database}
                                  </span>{' '}
                                  {t('archive_storage_label')}
                                </div>
                              </td>
                              <td className='arcm-border-0 arcm-text-gray-900 arcm-text-sm arcm-font-nomal arcm-text-right arcm-leading-none arcm-py-2'>
                                <div className='arcm-inline-flex arcm-items-center arcm-gap-2'>
                                  {AdminSettings.selected_database ? (
                                    <>
                                      {AdminSettings.selected_database ===
                                        'sqlite' && (
                                        <div className='arcm-inline-flex arcm-items-center arcm-gap-2'>
                                          <div class='icon arcm-flex arcm-justify-center arcm-items-center arcm-w-[29px] arcm-h-[29px] arcm-rounded-full arcm-bg-orange-50'>
                                            <svg
                                              xmlns='http://www.w3.org/2000/svg'
                                              width='14'
                                              height='14'
                                              viewBox='0 0 14 14'
                                              fill='none'
                                            >
                                              <path
                                                d='M13.5 1.75C13.5 0.783463 10.5899 0 7.00006 0C3.41018 0 0.5 0.783463 0.5 1.75C0.5 2.71654 3.41018 3.5 7.00006 3.5C10.5899 3.5 13.5 2.71654 13.5 1.75Z'
                                                fill='#BDDBFF'
                                              ></path>
                                              <path
                                                d='M7.00006 7C10.5885 7 13.5 6.2175 13.5 5.25V1.75C13.5 2.7175 10.5885 3.5 7.00006 3.5C3.41145 3.5 0.5 2.7175 0.5 1.75V5.25C0.5 6.2175 3.41145 7 7.00006 7Z'
                                                fill='#9BC9FF'
                                              ></path>
                                              <path
                                                d='M7.00006 10.5C10.5885 10.5 13.5 9.7175 13.5 8.75V5.25C13.5 6.2175 10.5885 7 7.00006 7C3.41145 7 0.5 6.2175 0.5 5.25V8.75C0.5 9.7175 3.41145 10.5 7.00006 10.5Z'
                                                fill='#57A4FF'
                                              ></path>
                                              <path
                                                d='M13.5 8.75C13.5 9.7175 10.5885 10.5 7.00006 10.5C3.41145 10.5 0.5 9.7175 0.5 8.75V12.25C0.5 13.2175 3.41145 14 7.00006 14C10.5885 14 13.5 13.2175 13.5 12.25V8.75Z'
                                                fill='#2488FF'
                                              ></path>
                                            </svg>
                                          </div>
                                          <span>
                                            {t('local_storage_label')}
                                          </span>
                                        </div>
                                      )}
                                      {AdminSettings.selected_database ===
                                        'rds' && (
                                        <div className='arcm-inline-flex arcm-items-center arcm-gap-2'>
                                          <span className='arcm-w-3.5 arcm-h-3.5 arcm-bg-[#27d935] arcm-rounded-full'></span>
                                          <span>{t('rds_label')}</span>
                                          <span>{arcmIcons.aws}</span>
                                        </div>
                                      )}
                                      {AdminSettings.selected_database ===
                                        'google_drive' && (
                                        <div className='arcm-inline-flex arcm-items-center arcm-gap-2'>
                                          <div class='icon arcm-flex arcm-justify-center arcm-items-center arcm-w-[29px] arcm-h-[29px] arcm-rounded-full arcm-bg-blue-50'>
                                            <svg
                                              xmlns='http://www.w3.org/2000/svg'
                                              width='14'
                                              height='14'
                                              viewBox='0 0 14 14'
                                              fill='none'
                                            >
                                              <path
                                                d='M7.5 2L2.5 11H12.5L7.5 2Z'
                                                fill='#4285F4'
                                              />
                                              <path
                                                d='M7.5 2L4.5 8H10.5L7.5 2Z'
                                                fill='#34A853'
                                              />
                                              <path
                                                d='M7.5 2L6.5 5H8.5L7.5 2Z'
                                                fill='#FBBC04'
                                              />
                                            </svg>
                                          </div>
                                          <span>{t('google_drive')}</span>
                                        </div>
                                      )}
                                    </>
                                  ) : (
                                    <div className='arcm-inline-flex arcm-items-center arcm-gap-2 arcm-text-gray-500'>
                                      {t('no_connection_set')}
                                    </div>
                                  )}
                                  {AdminSettings.selected_database ===
                                    'custom_mysql' && (
                                    <>
                                      <span className='arcm-w-3 arcm-h-3 arcm-bg-[#27d935] arcm-rounded-full'>
                                        {' '}
                                      </span>{' '}
                                      <span>{t('custom_mysql_database')}</span>
                                    </>
                                  )}
                                </div>
                              </td>
                            </tr>
                            <tr>
                              <td className='arcm-border-0 arcm-text-gray-700 arcm-text-sm arcm-font-semibold arcm-leading-none arcm-py-2'>
                                <div className=' arcm-inline-flex arcm-items-center arcm-gap-2'>
                                  <span className='icon'>
                                    {arcmIcons.folder}
                                  </span>{' '}
                                  {t('post_type_label')}
                                </div>
                              </td>
                              <td className='arcm-border-0 arcm-text-gray-900 arcm-text-sm arcm-font-nomal arcm-text-right arcm-leading-none arcm-py-2'>
                                <div className='arcm-inline-flex arcm-items-center arcm-gap-2'>
                                  {' '}
                                  {t('woocommerce_orders')}
                                </div>
                              </td>
                            </tr>
                            <tr>
                              <td className='arcm-border-0 arcm-text-gray-700 arcm-text-sm arcm-font-semibold arcm-leading-none arcm-py-2'>
                                <div className=' arcm-inline-flex arcm-items-center arcm-gap-2'>
                                  <span className='icon'>
                                    {arcmIcons.calendar}
                                  </span>{' '}
                                  {t('archive_range_label_colon')}
                                </div>
                              </td>
                              <td className='arcm-border-0 arcm-text-gray-900 arcm-text-sm arcm-font-nomal arcm-text-right arcm-leading-none arcm-py-2'>
                                <div className='arcm-inline-flex arcm-items-center arcm-gap-2'>
                                  {AdminSettings.archive_range
                                    ? AdminSettings.archive_range === 'custom_date' && AdminSettings.archive_range_datetime
                                      ? AdminSettings.archive_range_datetime
                                      : t(`archive_range_options.${AdminSettings.archive_range}`) || AdminSettings.archive_range.replace('_', ' ')
                                    : ''}
                                </div>
                              </td>
                            </tr>
                            <tr>
                              <td className='arcm-border-0 arcm-text-gray-700 arcm-text-sm arcm-font-semibold arcm-leading-none arcm-py-2'>
                                <div className=' arcm-inline-flex arcm-items-center arcm-gap-2'>
                                  <span className='icon'>
                                    {arcmIcons.autoArchive}
                                  </span>{' '}
                                  {t('auto_archive_schedule')}
                                </div>
                              </td>
                              <td className='arcm-border-0 arcm-text-gray-900 arcm-text-sm arcm-font-nomal arcm-text-right arcm-leading-none arcm-py-2'>
                                <div className='arcm-inline-flex arcm-items-center arcm-gap-2'>
                                  {'yes' === AdminSettings.enable_auto_archive
                                    ? AdminSettings.auto_archive_interval.replace(
                                        '_',
                                        ' '
                                      )
                                    : t('disabled')}
                                </div>
                              </td>
                            </tr>
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>

                  <div className='arcm-export-orders arcm-mt-4 arcm-px-5 arcm-py-6 sm:arcm-px-8 sm:arcm-py-10 md:arcm-px-10 md:arcm-py-12 arcm-bg-white arcm-rounded-lg arcm-border arcm-border-gray-200'>
                    <div className='arcm-text-gray-800 arcm-text-base arcm-font-bold arcm-mb-1.5'>
                      {t('export_orders')}
                    </div>
                    <div className='arcm-text-gray-600 arcm-text-sm arcm-font-normal arcm-mb-4'>
                      {t('export_orders_desc')}
                    </div>
                    <button
                      onClick={() => handleViewChange('export_orders')}
                      class='arcm-text-[#3858e9] 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 hover:arcm-bg-[#3858e9] hover:arcm-text-white'
                    >
                      <span className='icon'>
                        <svg
                          xmlns='http://www.w3.org/2000/svg'
                          width='18'
                          height='18'
                          viewBox='0 0 18 18'
                          fill='none'
                        >
                          <path
                            className='arcm-transition-all group-hover:arcm-stroke-white'
                            d='M1.5 12.75V14.625C1.5 15.6605 2.33947 16.5 3.375 16.5H14.625C15.6605 16.5 16.5 15.6605 16.5 14.625V12.75M12.75 9L9 12.75M9 12.75L5.25 9M9 12.75V1.5'
                            stroke='#3858E9'
                            stroke-width='1.5'
                            stroke-linecap='round'
                            stroke-linejoin='round'
                          />
                        </svg>
                      </span>
                      <span>{t('export_orders')}</span>
                    </button>
                  </div>
                </>
              )}
            </>
          )
        ) : null}
        {activeView === 'archive_settings' && (
          <connectionContext.Provider
            value={{
              awsConnection,
              handleAwsconnection,
              customMySQLConnection,
              handleCustomMySQLConnection
            }}
          >
            <ArchiveSettings
              AdminSettings={AdminSettings}
              setAdminSettings={setAdminSettings}
              googleDriveConnection={googleDriveConnection}
              setGoogleDriveConnection={setGoogleDriveConnection}
              onvVeiwChange={handleViewChange}
              isPro={isPro}
              falshDoor={falshDoor}
              handleOnboardingComplete={handleOnboardingComplete}
              saveAdminSettings={saveAdminSettings}
              saveBtnLoading={saveBtnLoading}
              archiving={archiving}
              handleArchiveModal={handleToggleModal}
              totalOrderToArchive={totalOrderToArchive}
              totalOrder={totalOrder}
              olderSchedule={olderSchedule}
              setTotalOrderToArchive={setTotalOrderToArchive}
              setArchivingOrderInfo={setArchivingOrderInfo}
              archivingDate={archivingDate}
              setArchivingDate={setArchivingDate}
              isOnboardingComplete={isOnboardingComplete}
              lastArchiveSettingsTab={lastArchiveSettingsTab}
              setLastArchiveSettingsTab={setLastArchiveSettingsTab}
            />
          </connectionContext.Provider>
        )}
        {activeView === 'aws_database' && (
          <connectionContext.Provider
            value={{
              awsConnection,
              handleAwsconnection,
              handleOnboardingComplete,
              rdsCredential,
              setRdsCredential
            }}
          >
            <AwsConfigure onvVeiwChange={handleViewChange} />
          </connectionContext.Provider>
        )}
        {activeView === 'custom_mysql_database' && (
          <connectionContext.Provider
            value={{
              customMySQLConnection,
              handleCustomMySQLConnection,
              handleOnboardingComplete,
              customMySQLCredential,
              setCustomMySQLCredential
            }}
          >
            <CustomMySQLConfigure onvVeiwChange={handleViewChange} />
          </connectionContext.Provider>
        )}
        {activeView === 'archiving_log' && (
          <Logs onvVeiwChange={handleViewChange} />
        )}
        {activeView === 'export_orders' && (
          <ExportOrders
            AdminSettings={AdminSettings}
            setAdminSettings={setAdminSettings}
            onvVeiwChange={handleViewChange}
            saveAdminSettings={saveAdminSettings}
            saveBtnLoading={saveBtnLoading}
            siteTotalOrder={siteTotalOrder}
          />
        )}

        <Modal openModal={isOpen} toggleModal={handleToggleModal}>
          {{
            header: (
              <h5 className='arcm-text-gray-800 arcm-text-lg sm:arcm-text-xl arcm-font-bold'>
                {t('archive_options')}
              </h5>
            ),
            body: (
              <div className='arcm-mb-6 arcm-mt-3'>
                <table className='arcm-w-full arcm-mb-4'>
                  <tbody>
                    <tr>
                      <td className='arcm-text-gray-700 arcm-text-sm arcm-font-semibold arcm-leading-none arcm-py-2'>
                        <div className='arcm-inline-flex arcm-items-center arcm-gap-2'>
                          <span className='icon'>{arcmIcons.database}</span>
                          {t('archive_storage')}
                        </div>
                      </td>
                      <td className='arcm-text-gray-900 arcm-text-sm arcm-font-normal arcm-text-right arcm-leading-none arcm-py-2'>
                        <div className='arcm-inline-flex arcm-items-center arcm-gap-2'>
                          {AdminSettings.selected_database ? (
                            <>
                              {AdminSettings.selected_database === 'sqlite' && (
                                <div className='arcm-inline-flex arcm-items-center arcm-gap-2'>
                                  <div class='icon arcm-flex arcm-justify-center arcm-items-center arcm-w-[29px] arcm-h-[29px] arcm-rounded-full arcm-bg-orange-50'>
                                    <svg
                                      xmlns='http://www.w3.org/2000/svg'
                                      width='14'
                                      height='14'
                                      viewBox='0 0 14 14'
                                      fill='none'
                                    >
                                      <path
                                        d='M13.5 1.75C13.5 0.783463 10.5899 0 7.00006 0C3.41018 0 0.5 0.783463 0.5 1.75C0.5 2.71654 3.41018 3.5 7.00006 3.5C10.5899 3.5 13.5 2.71654 13.5 1.75Z'
                                        fill='#BDDBFF'
                                      ></path>
                                      <path
                                        d='M7.00006 7C10.5885 7 13.5 6.2175 13.5 5.25V1.75C13.5 2.7175 10.5885 3.5 7.00006 3.5C3.41145 3.5 0.5 2.7175 0.5 1.75V5.25C0.5 6.2175 3.41145 7 7.00006 7Z'
                                        fill='#9BC9FF'
                                      ></path>
                                      <path
                                        d='M7.00006 10.5C10.5885 10.5 13.5 9.7175 13.5 8.75V5.25C13.5 6.2175 10.5885 7 7.00006 7C3.41145 7 0.5 6.2175 0.5 5.25V8.75C0.5 9.7175 3.41145 10.5 7.00006 10.5Z'
                                        fill='#57A4FF'
                                      ></path>
                                      <path
                                        d='M13.5 8.75C13.5 9.7175 10.5885 10.5 7.00006 10.5C3.41145 10.5 0.5 9.7175 0.5 8.75V12.25C0.5 13.2175 3.41145 14 7.00006 14C10.5885 14 13.5 13.2175 13.5 12.25V8.75Z'
                                        fill='#2488FF'
                                      ></path>
                                    </svg>
                                  </div>
                                  <span>{t('local_storage_label')}</span>
                                </div>
                              )}
                              {AdminSettings.selected_database === 'rds' && (
                                <div className='arcm-inline-flex arcm-items-center arcm-gap-2'>
                                  <span className='arcm-w-3.5 arcm-h-3.5 arcm-bg-[#27d935] arcm-rounded-full'></span>
                                  <span>{t('rds_label')}</span>
                                  <span>{arcmIcons.aws}</span>
                                </div>
                              )}
                              {AdminSettings.selected_database ===
                                'google_drive' && (
                                <div className='arcm-inline-flex arcm-items-center arcm-gap-2'>
                                  <div class='icon arcm-flex arcm-justify-center arcm-items-center arcm-w-[29px] arcm-h-[29px] arcm-rounded-full arcm-bg-blue-50'>
                                    <svg
                                      xmlns='http://www.w3.org/2000/svg'
                                      width='14'
                                      height='14'
                                      viewBox='0 0 14 14'
                                      fill='none'
                                    >
                                      <path
                                        d='M7.5 2L2.5 11H12.5L7.5 2Z'
                                        fill='#4285F4'
                                      />
                                      <path
                                        d='M7.5 2L4.5 8H10.5L7.5 2Z'
                                        fill='#34A853'
                                      />
                                      <path
                                        d='M7.5 2L6.5 5H8.5L7.5 2Z'
                                        fill='#FBBC04'
                                      />
                                    </svg>
                                  </div>
                                  <span>{t('google_drive')}</span>
                                </div>
                              )}
                            </>
                          ) : (
                            <div className='arcm-inline-flex arcm-items-center arcm-gap-2 arcm-text-gray-500'>
                              {t('no_connection_set')}
                            </div>
                          )}
                          {AdminSettings.selected_database === 'custom_mysql' && (
                            <>
                              <span className='arcm-w-3 arcm-h-3 arcm-bg-[#27d935] arcm-rounded-full'></span>
                              <span className='arcm-font-semibold arcm-text-gray-900'>
                                {t('custom_mysql_database')}
                              </span>
                            </>
                          )}
                        </div>
                      </td>
                    </tr>
                    <tr>
                      <td className='arcm-text-gray-700 arcm-text-sm arcm-font-semibold arcm-leading-none arcm-py-2'>
                        <div className='arcm-inline-flex arcm-items-center arcm-gap-2'>
                          <span className='icon'>{arcmIcons.folder}</span>
                          {t('post_type_label')}
                        </div>
                      </td>
                      <td className='arcm-text-gray-900 arcm-text-sm arcm-font-normal arcm-text-right arcm-leading-none arcm-py-2'>
                        <div className='arcm-inline-flex arcm-items-center arcm-gap-2'>
                          {t('woocommerce_orders')}
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>
                {/* Statuses */}
                <div className='arcm-mb-2 arcm-text-center'>
                  <span className='arcm-font-semibold arcm-text-gray-700'>
                    {t('statuses')}:
                  </span>
                  <span className='arcm-text-gray-900 arcm-ml-1'>
                    {(AdminSettings.archive_statuses || [])
                      .map(
                        status =>
                          status
                            .replace(/^wc-/, '') // Remove "wc-" prefix
                            .replace(/-/g, '') // Remove hyphens
                            .replace(/^\w/, c => c.toUpperCase()) // Capitalize first letter
                      )
                      .join(', ')}
                  </span>
                </div>
                {/* Exclusion/Warning info */}
                <div className='arcm-mb-4 arcm-text-center'>
                  {/* Show enabled info if either is excluded */}
                  {(AdminSettings.exclude_subscriptions ||
                    AdminSettings.exclude_memberships) && (
                    <div className='arcm-text-[13px] arcm-mb-2'>
                      {AdminSettings.exclude_subscriptions &&
                        AdminSettings.exclude_memberships && (
                          <span className='arcm-text-green-700'>
                            {t('subscriptions_and_membership_orders_excluded')}
                          </span>
                        )}
                      {AdminSettings.exclude_subscriptions &&
                        !AdminSettings.exclude_memberships && (
                          <span className='arcm-text-green-700'>
                            {t('subscriptions_orders_excluded')}
                          </span>
                        )}
                      {!AdminSettings.exclude_subscriptions &&
                        AdminSettings.exclude_memberships && (
                          <span className='arcm-text-green-700'>
                            {t('membership_orders_excluded')}
                          </span>
                        )}
                    </div>
                  )}
                  {/* Show warning if either is NOT excluded */}
                  {((!AdminSettings.exclude_subscriptions &&
                    activePlugins.has_subscriptions &&
                    Object.keys(activePlugins.has_subscriptions).length > 0) ||
                    (!AdminSettings.exclude_memberships &&
                      activePlugins.has_memberships &&
                      Object.keys(activePlugins.has_memberships).length >
                        0)) && (
                    <div className='arcm-flex arcm-justify-center arcm-w-full arcm-text-center'>
                      <svg
                        width='19'
                        height='17'
                        viewBox='0 0 19 17'
                        fill='none'
                        xmlns='http://www.w3.org/2000/svg'
                        style={{
                          minWidth: 19,
                          minHeight: 17,
                          marginLeft: 10,
                          marginTop: 1
                        }}
                      >
                        <polygon points='9,2 17,15 1,15' fill='#F97316' />
                        <text
                          x='9'
                          y='12'
                          textAnchor='middle'
                          fontSize='10'
                          fill='#fff'
                          fontFamily='Arial'
                          fontWeight='bold'
                        >
                          !
                        </text>
                      </svg>
                      <span className='arcm-text-[#F97316] arcm-mr-[10px] arcm-text-[13px] arcm-font-medium arcm-text-center'>
                        {(() => {
                          // Both excluded = no warning, so this only renders if at least one is NOT excluded
                          const bothDisabled =
                            !AdminSettings.exclude_subscriptions &&
                            activePlugins.has_subscriptions &&
                            Object.keys(activePlugins.has_subscriptions)
                              .length > 0 &&
                            !AdminSettings.exclude_memberships &&
                            activePlugins.has_memberships &&
                            Object.keys(activePlugins.has_memberships).length >
                              0
                          if (bothDisabled) {
                            return (
                              <>
                                {t('archiving_subscriptions_memberships_warning_1')}{' '}
                                <span
                                  className='arcm-text-[#F97316] arcm-font-medium arcm-underline arcm-cursor-pointer'
                                  onClick={() => {
                                    setActiveView('archive_settings')
                                    handleToggleModal()
                                  }}
                                >
                                  {t('archive_settings')}
                                </span>{' '}
                                {t('archiving_subscriptions_memberships_warning_2')}
                              </>
                            )
                          }
                          if (
                            !AdminSettings.exclude_subscriptions &&
                            activePlugins.has_subscriptions &&
                            Object.keys(activePlugins.has_subscriptions)
                              .length > 0
                          ) {
                            return (
                              <>
                                {t('archiving_subscriptions_warning_1')}{' '}
                                <span
                                  className='arcm-text-[#F97316] arcm-font-medium arcm-underline arcm-cursor-pointer'
                                  onClick={() => {
                                    setActiveView('archive_settings')
                                    handleToggleModal()
                                  }}
                                >
                                  {t('archive_settings')}
                                </span>{' '}
                                {t('archiving_subscriptions_warning_2')}
                              </>
                            )
                          }
                          if (
                            !AdminSettings.exclude_memberships &&
                            activePlugins.has_memberships &&
                            Object.keys(activePlugins.has_memberships).length >
                              0
                          ) {
                            return (
                              <>
                                {t('archiving_memberships_warning_1')}{' '}
                                <span
                                  className='arcm-text-[#F97316] arcm-font-medium arcm-underline arcm-cursor-pointer'
                                  onClick={() => {
                                    setActiveView('archive_settings')
                                    handleToggleModal()
                                  }}
                                >
                                  {t('archive_settings')}
                                </span>{' '}
                                {t('archiving_memberships_warning_2')}
                              </>
                            )
                          }
                          return null
                        })()}
                      </span>
                    </div>
                  )}
                </div>
                <div className='btn-box arcm-flex arcm-flex-col arcm-items-center arcm-justify-center'>
                  <button
                    type='button'
                    onClick={ () => handleArchiveing('archiving__start')}
                    disabled={startArchivingLoading}
                    className='arcm-mb-4 arcm-flex arcm-min-w-[180px] arcm-items-center arcm-justify-center arcm-gap-2 arcm-rounded-lg arcm-bg-[#3858e9] arcm-px-4 arcm-py-2.5 arcm-text-sm arcm-font-semibold arcm-text-white arcm-transition-all hover:arcm-bg-blue-700 disabled:arcm-cursor-not-allowed disabled:arcm-opacity-70'
                  >
                    {startArchivingLoading ? (
                      <>
                        <span className='icon'>{arcmIcons.spinning}</span>
                        {t('loading')}
                      </>
                    ) : (
                      t('start_archiving')
                    )}
                  </button>
                  <button
                    type='button'
                    onClick={handleToggleModal}
                    disabled={startArchivingLoading}
                    className='arcm-min-w-[180px] arcm-rounded-lg arcm-border arcm-border-[#EF4444] arcm-bg-white arcm-px-4 arcm-py-2.5 arcm-text-sm arcm-font-semibold arcm-text-[#EF4444] arcm-transition-all hover:arcm-border-[#F1F5F9] hover:arcm-bg-[#F1F5F9] hover:arcm-text-[#111827] disabled:arcm-cursor-not-allowed disabled:arcm-opacity-60'
                  >
                    {t('cancel')}
                  </button>
                </div>
              </div>
            )
          }}
        </Modal>

        <Modal
          openModal={isArchiveFailedOpen}
          toggleModal={handleArchiveFailedToggleModal}
        >
          {{
            header: (
              <h5 className='arcm-text-center arcm-text-gray-800 arcm-text-lg sm:arcm-text-xl arcm-font-bold'>
                {t('no_orders_to_archive')}
              </h5>
            ),
            body: (
              <div className='arcm-mb-6'>
                <p className='arcm-text-red-500 arcm-text-sm arcm-font-normal'>
                  {archiveFailMeassage}
                </p>
              </div>
            )
          }}
        </Modal>

        <Modal
          openModal={isArchiveCancel}
          toggleModal={handelCancelArchivingModal}
          isCrossBtnDisabled={cancelBtnLoading}
          outerClick={!cancelBtnLoading}
        >
          {{
            header: isCancelled ? (
              <h2 className='arcm-text-2xl arcm-font-bold arcm-text-red-500 arcm-mb-4'>
                {t('archiving_cancelled')}
              </h2>
            ) : (
              <h5 className='arcm-text-gray-800 arcm-text-lg sm:arcm-text-xl arcm-font-bold'>
                {t('cancel_archiving_process')}
              </h5>
            ),
            body: isCancelled ? (
              <>
                <p className='arcm-text-lg arcm-mb-3'>
                  <span className='arcm-font-semibold'>{archivedOrders}</span>{' '}
                  out of{' '}
                  <span className='arcm-font-semibold'>
                    {totalArchiveOrders}
                  </span>{' '}
                  {t('orders_have_been_archived')}
                </p>

                <p className='arcm-text-gray-700 arcm-mb-6'>
                  {t('restore_archived_orders_1')}{' '}
                  <a
                    href='/archived-orders'
                    className='arcm-text-blue-600 arcm-underline'
                  >
                    {t('archived_orders')}
                  </a>{' '}
                  {t('restore_archived_orders_2')}
                </p>

                <div className='arcm-flex arcm-justify-center arcm-mt-6'>
                  <button
                    onClick={handelCancelArchivingModal}
                    className='arcm-min-w-[120px] arcm-bg-[#F3F4F6] arcm-text-gray-900 arcm-font-medium arcm-py-2.5 arcm-px-4 arcm-rounded-lg hover:arcm-bg-gray-200 arcm-transition-colors'
                  >
                    {t('close')}
                  </button>
                </div>
              </>
            ) : (
              <div className='arcm-text-center arcm-mb-6'>
                <p className='arcm-text-gray-900 arcm-text-sm arcm-font-normal'>
                  {t('cancel_archiving_confirm')}
                </p>
                <div className='btn-box arcm-flex arcm-flex-wrap arcm-gap-4 arcm-mt-6'>
                  <button
                    onClick={handelCancelArchiving}
                    disabled={cancelBtnLoading}
                    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'
                  >
                    {cancelBtnLoading ? (
                      <>
                        <span className='icon'>{arcmIcons.spinning}</span>
                        {t('cancelling')}
                      </>
                    ) : (
                      t('cancel_archiving')
                    )}
                  </button>
                  <button
                    onClick={handelCancelArchivingModal}
                    disabled={cancelBtnLoading}
                    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>
      </div>

      <FlexOrderPromoModal 
        isOpen={isFlexOrderModalOpen} 
        onClose={handleFlexOrderModalClose} 
        activeOrders={siteTotalOrder} 
      />
    </>
  )
}

export default Settings
