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

export const ArchivedOrderContext = createContext(null)

export default function ArchivedOrderProvider({ children }) {
  const { t } = useTranslations()

  // All state variables from ArchivedOrder.jsx
  const [orders, setOrders] = useState([])
  const [activeView, setActiveView] = useState('archived_orders')
  const [isPro, setIsPro] = useState(false)
  const [tableLoading, setTableLoading] = useState(false)
  const [selectAll, setSelectAll] = useState(false)
  const [bulkAction, setBulkAction] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const [totaOrderNumber, setTotaOrderNumber] = useState(0)
  const [modalLoading, setmodalLoading] = useState(false)
  const [isOpenUnarchiveModal, setIsOpenUnarchiveModal] = useState(false)
  const [isStartUnarchiveModal, setIsStartUnarchiveModal] = useState(false)
  const [startBgUnarchiving, setStartBgUnarchiving] = useState('')
  const [modalTile, setmodalTile] = useState(t('unarchiving_order'))
  const [modaDesc, setmodaDesc] = useState('')
  const [ordersPerPage, setOrdersPerPage] = useState(10)
  const [singleOrderId, setSingleOrderId] = useState(0)
  const [exportLoading, setExportLoading] = useState(false)
  const [unArchivingStatus, setUnArchivingStatus] = useState('')
  const [isUnarchiveCancelModal, setIsUnarchiveCancelModal] = useState(false)
  const [cancelUnarchiveBtnLoading, setCancelUnarchiveBtnLoading] = useState(false)
  const [unArchvedOrder, setUnarchvedOrder] = useState(0)
  const [totalUnArchvedOrder, setTotalUnArchvedOrder] = useState(0)
  const [isUnarchiveCancel, setIsUnarchiveCancel] = useState(false)
  const [selectedOrders, setSelectedOrders] = useState([])
  const [allowDplicateUnarchive, setAllowDplicateUnarchive] = useState(false)
  const [percentage, setPercentage] = useState(0)
  const [unarchivePercentage, setUnarchivePercentage] = useState(0)
  const [exportStatus, setExportStatus] = useState('')
  const [exportFileName, setExportFileName] = useState('')
  const [exportFormat, setExportFormat] = useState('json')
  const [exportDownloadUrl, setExportDownloadUrl] = useState('')
  const [exportSortType, setExportSortType] = useState('ASC')
  const [lastExportTime, setLastExportTime] = useState('')
  const [isOpenExportModal, setIsOpenExportModal] = useState(false)
  const [isOpenExportCancelModal, setIsOpenExportCancelModal] = useState(false)
  const [cancelExportBtnLoading, setCancelExportBtnLoading] = useState(false)
  const [settingOffTooltip, setSettingOffTooltip] = useState(false)
  const [isEmptyOrderModal, setIsEmptyOrderModal] = useState(false)
  const [emptyOrderTitle, setEmptyOrderTitle] = useState('')
  const [isOpenDeleteConfirmModal, setIsOpenDeleteConfirmModal] = useState(false)
  const [deleteLoading, setDeleteLoading] = useState(false)

  // Duplicate check states
  const [isOpenDuplicateModal, setIsOpenDuplicateModal] = useState(false)
  const [duplicateOrders, setDuplicateOrders] = useState([])
  const [duplicateCheckLoading, setDuplicateCheckLoading] = useState(false)
  const [singleDuplicateCheckLoading, setSingleDuplicateCheckLoading] = useState(false)
  const [duplicatOrderText, setduplicatOrderText] = useState('')

  // Sync Archive Data states
  const [isSyncModalOpen, setIsSyncModalOpen] = useState(false)
  const [syncLoading, setSyncLoading] = useState(false)
  const [selectedDatabase, setSelectedDatabase] = useState('')
  const [ordserListTxt, setOrdserListTxt] = useState('')

  // Search state
  const [searchQuery, setSearchQuery] = useState('')

  // Filter states
  const [filterStatus, setFilterStatus] = useState(() => {
    const statuses = window?.archm_admin?.orderStatuses || []
    return statuses.reduce((acc, status) => {
      const statusKey = status.value.replace('wc-', '')
      acc[statusKey] = false
      return acc
    }, {})
  })
  const [filterDateRange, setFilterDateRange] = useState({
    fromDate: '',
    toDate: ''
  })

  // Database connection state (assuming this was missing from the reads)
  const [dbConnected, setDbConnected] = useState(true)

  // Track if sync from Google Drive resulted in empty orders
  const [isSyncEmptyResult, setIsSyncEmptyResult] = useState(false)

  // Calculate pagination details
  const totalPages = Math.ceil(parseInt(totaOrderNumber) / ordersPerPage)
  const startIndex = (currentPage - 1) * ordersPerPage

  // Toggle select all orders
  const handleSelectAll = () => {
    const newSelectAll = !selectAll
    setSelectAll(newSelectAll)
    setOrders(orders.map(order => ({ ...order, is_selected: newSelectAll })))
  }

  // Toggle select individual order
  const handleSelectOrder = id => {
    const updatedOrders = orders.map(order =>
      order.id === id ? { ...order, is_selected: !order.is_selected } : order
    )
    setOrders(updatedOrders)
    setSelectAll(updatedOrders.every(order => order.isSelected))
  }

  // Clear search and reset to default view
  const handleClearSearch = () => {
    setSearchQuery('')

    // Reset filters to default
    const statuses = window?.archm_admin?.orderStatuses || []
    const resetStatuses = statuses.reduce((acc, status) => {
      const statusKey = status.value.replace('wc-', '')
      acc[statusKey] = false
      return acc
    }, {})
    setFilterStatus(resetStatuses)
    setFilterDateRange({ fromDate: '', toDate: '' })

    // Ensure we fetch first page with default filters
    if (currentPage !== 1) {
      setCurrentPage(1)
    } else {
      getArchivedOrder({
        filter_status: [],
        filter_date_from: '',
        filter_date_to: ''
      })
    }
  }

  // Handle status filter change
  const handleStatusFilterChange = status => {
    setFilterStatus(prev => ({
      ...prev,
      [status]: !prev[status]
    }))
  }

  // Handle date filter change
  const handleDateFilterChange = (type, value) => {
    setFilterDateRange(prev => ({
      ...prev,
      [type]: value
    }))
  }

  // Check if any filter is active
  const isAnyFilterActive = () => {
    const hasActiveStatus = Object.values(filterStatus).some(
      status => status === true
    )
    const hasDateFilter =
      filterDateRange.fromDate !== '' || filterDateRange.toDate !== ''
    return hasActiveStatus || hasDateFilter
  }

  // Handle clear filter
  const handleClearFilter = () => {
    const statuses = window?.archm_admin?.orderStatuses || []
    const resetStatuses = statuses.reduce((acc, status) => {
      const statusKey = status.value.replace('wc-', '')
      acc[statusKey] = false
      return acc
    }, {})
    setFilterStatus(resetStatuses)
    setFilterDateRange({
      fromDate: '',
      toDate: ''
    })
    getArchivedOrder({
      filter_status: [],
      filter_date_from: '',
      filter_date_to: ''
    })
  }

  // Apply filter
  const handleApplyFilter = () => {
    getArchivedOrder()
  }

  // Handle search
  const handleSearch = async () => {
    setTableLoading(true)
    setCurrentPage(1)
    setIsSyncEmptyResult(false) // Reset sync empty result when searching

    try {
      const activeStatuses = Object.entries(filterStatus)
        .filter(([_, checked]) => checked)
        .map(([status]) => status)

      const response = await makeApiRequest('search-orders', 'POST', {
        search: searchQuery,
        ordersPerPage,
        startIndex: 0,
        filter_status: activeStatuses,
        filter_date_from: filterDateRange.fromDate,
        filter_date_to: filterDateRange.toDate
      })

      if (response.success) {
        setOrders(response.data.orders)
        setTotaOrderNumber(response.data.total_order)
      } else {
        if (response.data?.dbConnectionError) {
          setDbConnected(false)
        }
        setOrders([])
        setTotaOrderNumber(0)
      }
    } catch (error) {
      console.error('Search failed:', error)
      setOrders([])
      setTotaOrderNumber(0)
    }

    setTableLoading(false)
  }

  // Get Selected Order
  const getSelectedOrder = () => {
    const selectedOrder = orders.filter(order => order.is_selected)
    return selectedOrder
  }

  // Check for duplicate orders before unarchiving
  const checkSingleDuplicateOrders = async orders => {
    try {
      let orderIds = orders.map(order => order.archived_order_id)

      const response = await makeApiRequest('check-duplicate-orders', 'POST', {
        orderIds: orderIds
      })

      if (response.success) {
        if (response.data.hasDuplicates) {
          let dupLicateID = response.data.duplcateOrders[0].ID
          let getSelectedOrder = orders.filter(
            order => parseInt(order.archived_order_id) === parseInt(dupLicateID)
          )

          setDuplicateOrders(getSelectedOrder)
          setduplicatOrderText(
            `This order ID is already exist in your live database. Unarchiving will change the order ID`
          )
          setOrdserListTxt(
            `Please choose how you'd like to proceed with this order`
          )
          setIsOpenDuplicateModal(true)
        } else {
          proceedWithUnarchive(orders)
        }
      } else {
        alert('Failed to check for duplicate orders. Please try again.')
      }
    } catch (error) {
      console.error('Duplicate check failed:', error)
      alert('Error checking for duplicate orders. Please try again.')
    }

    setSingleDuplicateCheckLoading(false)
  }

  // Proceed with unarchiving after duplicate check
  const proceedWithUnarchive = orders => {
    setmodalLoading(true)
    handleUnarchiveModal()
    performUnarchive(orders)
  }

  // Handle continue from duplicate modal
  const handleContinueUnarchive = () => {
    setSelectedOrders(duplicateOrders)
    setIsOpenDuplicateModal(false)
    setDuplicateOrders([])
    setAllowDplicateUnarchive(true)
  }

  // Handle cancel from duplicate modal
  const handleCancelUnarchive = () => {
    setIsOpenDuplicateModal(false)
    setUnArchivingStatus('')
    setDuplicateOrders([])
    deleteDuplicateToSkip()
  }

  // Delete duplicate order for skip
  const deleteDuplicateToSkip = async () => {
    const response = await Ajax.post('skip_duplicate_orders')
    if (response.success) {
      console.log('Skiped unarchive duplicate orders')
    }
  }

  // Handle duplicate modal toggle
  const handleDuplicateModal = () => {
    setIsOpenDuplicateModal(!isOpenDuplicateModal)
  }

  // Handle start unarchive modal
  const handleStartUnarchiveModal = () => {
    setIsStartUnarchiveModal(!isStartUnarchiveModal)
  }

  // Delete order from remote database
  const deleteOrder = async orders => {
    const orderIds = selectedOrders
      .filter(order => orders.includes(parseInt(order.archived_order_id)))
      .map(order => order.id)
    
    const deleteRemoteOrders = await makeApiRequest(
      'delete-unarchived-orders',
      'POST',
      orderIds
    )
    if (deleteRemoteOrders.success) {
      setmodalTile(t('unarchiving_process_complete'))
      setmodaDesc('')
      setmodalLoading(false)
      setAllowDplicateUnarchive(false)
      setUnArchivingStatus('')
      handleSearch()
    }
  }

  // Set bulk duplicate modal
  const setBulkDuplicateModal = orderLength => {
    setduplicatOrderText(
      `<strong> ${
        duplicateOrders.length > 0 ? duplicateOrders.length : orderLength
      } orders </strong> in your live store already have the same Order IDs as those you are trying to unarchive`
    )
    setOrdserListTxt(
      `Please choose how you'd like to proceed with these orders`
    )
  }

  // Perform the actual unarchiving
  const performUnarchive = async orders => {
    const unarchiveOrders = await makeApiRequest('unarchive-orders', 'POST', {
      orders,
      unarciev_status: unArchivingStatus,
      allow_duplicate_unarchiving: allowDplicateUnarchive
    })
    
    if (unarchiveOrders.success) {
      if (unarchiveOrders.data.unarchiveOrder.length > 0) {
        deleteOrder(unarchiveOrders.data.unarchiveOrder)
      }
      if (0 === unarchiveOrders.data.duplicateOrders.length) {
        setDuplicateCheckLoading(false)
      }
    } else {
      setmodalTile(t('unarchiving_process_failed'))
    }
  }

  const proceedBgUnArchiving = () => {
    setStartBgUnarchiving('start-unarchiving')
    setUnArchivingStatus('bulk')
    handleStartUnarchiveModal()
  }

  const proceedDuplicateBgUnArchiving = () => {
    setStartBgUnarchiving('start-unarchiving')
    setUnArchivingStatus('bulk')
    setAllowDplicateUnarchive(true)
    setDuplicateOrders([])
    handleDuplicateModal()
  }

  // Single order unarchive
  const singleOrderUnarchive = orderId => {
    setSingleOrderId(parseInt(orderId))
    setUnArchivingStatus('single')
    const order = orders.filter(order => order.id === orderId)
    setSelectedOrders(order)
  }

  // Handle bulk actions
  const handleBulkAction = () => {
    const selectedOrders = getSelectedOrder()
    if (selectedOrders.length === 0) {
      alert(t('please_select_order'))
      return
    }

    if (bulkAction === 'unarchive') {
      setSelectedOrders(selectedOrders)
      handleStartUnarchiveModal()
    } else if (bulkAction === 'permanently_delete') {
      setSelectedOrders(selectedOrders)
      setIsOpenDeleteConfirmModal(true)
    } else {
      alert(t('no_bulk_action'))
    }
  }

  // Handle permanent deletion of orders
  const handlePermanentDelete = async () => {
    try {
      setDeleteLoading(true)
      const response = await makeApiRequest(
        'permanently-delete-orders',
        'POST',
        {
          orders: selectedOrders
        }
      )

      if (response.success) {
        setIsOpenDeleteConfirmModal(false)
        setSelectedOrders([])
        getArchivedOrder()
        setEmptyOrderTitle(t('orders_permanently_deleted'))
        setIsEmptyOrderModal(true)
      } else {
        setEmptyOrderTitle(t('failed_to_delete_orders'))
        setIsEmptyOrderModal(true)
      }
    } catch (error) {
      console.error('Delete failed:', error)
      alert(t('failed_to_delete_orders'))
    } finally {
      setDeleteLoading(false)
    }
  }

  // Get archived orders from server
  const getArchivedOrder = async (override = {}) => {
    setTableLoading(true)
    // Reset sync empty result when fetching orders normally (not from sync)
    if (!override.isSyncCall) {
      setIsSyncEmptyResult(false)
    }
    
    const activeStatuses =
      typeof override.filter_status !== 'undefined'
        ? override.filter_status
        : Object.entries(filterStatus)
            .filter(([_, checked]) => checked)
            .map(([status]) => status)

    const resolvedFromDate =
      typeof override.filter_date_from !== 'undefined'
        ? override.filter_date_from
        : filterDateRange.fromDate

    const resolvedToDate =
      typeof override.filter_date_to !== 'undefined'
        ? override.filter_date_to
        : filterDateRange.toDate

    const archivedData = await makeApiRequest('get-archived-order', 'POST', {
      ordersPerPage,
      startIndex,
      filter_status: activeStatuses,
      filter_date_from: resolvedFromDate,
      filter_date_to: resolvedToDate
    })
    
    if (archivedData.success) {
      const { orders, total_order } = archivedData.data
      setOrders(orders)
      setTotaOrderNumber(total_order)
      setTableLoading(false)
      return { success: true, orders, total_order }
    } else {
      if (archivedData.data?.dbConnectionError) {
        setDbConnected(false)
      }
      setOrders([])
      setTotaOrderNumber(0)
      setTableLoading(false)
      return { success: false, orders: [], total_order: 0 }
    }
  }

  // Handle pagination
  const handlePageChange = page => {
    if (page >= 1 && page <= totalPages) {
      setCurrentPage(page)
    }
  }

  // Handle close open unarchiving modal
  const handleUnarchiveModal = () => {
    if (isOpenUnarchiveModal) {
      setmodalTile(t('unarchiving_order'))
    }
    setIsOpenUnarchiveModal(!isOpenUnarchiveModal)
  }

  // Handle unarchive cancel modal
  const handleUnarchiveCancelModal = () => {
    setIsUnarchiveCancelModal(!isUnarchiveCancelModal)
  }

  // Handle close open export modal
  const handleIsOpenExportModal = () => {
    setIsOpenExportModal(!isOpenExportModal)
  }

  // Handle modal for empty order
  const handleIsEmptyOrderModal = () => {
    setIsEmptyOrderModal(!isEmptyOrderModal)
  }

  // Sync Archive Data handlers
  const handleSyncModal = () => {
    setIsSyncModalOpen(!isSyncModalOpen)
  }

  const handleSyncArchiveData = async () => {
    setSyncLoading(true)
    setIsSyncEmptyResult(false) // Reset empty result state
    try {
      const response = await makeApiRequest('recover-archive-data', 'POST')

      if (response.success) {
        setIsSyncModalOpen(false)
        
        // Fetch orders after sync and check if empty
        const orderResult = await getArchivedOrder({ isSyncCall: true })
        
        // Check if orders are empty after sync (regardless of success flag)
        // Empty orders after sync means the Google Drive file has no orders
        if (orderResult.orders.length === 0 && orderResult.total_order === 0) {
          setIsSyncEmptyResult(true)
          // Show toast message for empty orders
          if (window.Siz) {
            window.Siz.success(`<p>Successfully synced the file form Google Drive!<span style="color: red;"> But no order found in the file.</span></p>`, 4000)
          }
        } else {
          setIsSyncEmptyResult(false)
          // Show success message
          if (window.Siz) {
            window.Siz.success('Successfully synced with Google Drive!', 4000)
          }
        }

        if (window.wp && window.wp.hooks) {
          window.wp.hooks.doAction('archm_sqlite_changed')
        }
      } else {
        if (window.Siz) {
          window.Siz.error('Failed to sync archive data', 4000)
        }
      }
    } catch (error) {
      console.error('Sync error:', error)
      alert(t('sync_error') || 'An error occurred while syncing archive data')
    } finally {
      setSyncLoading(false)
    }
  }

  const showBulkDuplicateModal = () => {
    if (duplicateOrders.length > 0) {
      setBulkDuplicateModal()
      setIsOpenDuplicateModal(true)
      setDuplicateCheckLoading(false)
    }
  }

  // Handle export cancel modal
  const handleExportCancelModal = () => {
    setIsOpenExportCancelModal(!isOpenExportCancelModal)
  }

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

  // Handle cancel unarchiving
  const handelCancelUnarchiving = async () => {
    setCancelUnarchiveBtnLoading(true)
    const response = await Ajax.post('cancel_archiving')
    if (response.success) {
      let archiveInfo = response.data
      setUnarchvedOrder(parseInt(archiveInfo.unarchived_order))
      setTotalUnArchvedOrder(parseInt(archiveInfo.total_orders))
      setIsUnarchiveCancel(true)
      setStartBgUnarchiving('unarchive-cancel')
      setUnarchivePercentage(0)
    }
  }

  // Export order
  const exportOrder = async () => {
    handleIsOpenExportModal()
    try {
      setExportStatus('start-exporting')
      const response = await Ajax.post('start_export_orders', {
        sort_type: exportSortType,
        export_format: exportFormat,
        order_source: 'archived'
      })

      if (response.success) {
        fetchExportingStatus()
      } else {
        setExportStatus('export-cancel')
        handleIsEmptyOrderModal()
        setEmptyOrderTitle(response.message)
      }
    } catch (error) {
      console.error('error:', error)
      alert('Error exportng order.')
    }
  }

  const unarchiveAllOrder = async () => {
    try {
      setUnArchivingStatus('start-unarchiving')
      setUnarchvedOrder(0)
      setTotalUnArchvedOrder(0)

      const response = await Ajax.post('start_unarchive_orders', {
        bulk_selected_order: selectedOrders,
        allow_duplicate_orders: allowDplicateUnarchive
      })

      if (response.success) {
        setSelectedOrders([])
        fetchUnarchivegStatus()
      } else {
        setStartBgUnarchiving('unarchive-cancel')
        handleIsEmptyOrderModal(!isEmptyOrderModal)
        setEmptyOrderTitle(response.message)
      }
    } catch (error) {
      console.error('error:', error)
      alert('Error unarchive order.')
    }
  }

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

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

    return formattedDate
  }

  // Fetch exporting status
  const fetchExportingStatus = async () => {
    const response = await Ajax.post('check_export_progress')
    if (response.success) {
      let jobStauts = Object.values(response.data)[0]
      setPercentage(parseInt(jobStauts.progress))
      
      if ('processing' === jobStauts.status) {
        setTimeout(() => fetchExportingStatus(), 1000)
      } else {
        if (!exportFileName) {
          setExportFileName(jobStauts.file_name)
        }
        setExportDownloadUrl(jobStauts.download_url)
        setLastExportTime(formateLastExportDate(jobStauts.updated_at))
        setTimeout(() => {
          if ('cancelled' === jobStauts.status) {
            setExportStatus('export-cancel')
          } else if ('completed' === jobStauts.status) {
            setExportStatus('export-complete')
          }
          setPercentage(0)
        }, 2000)
      }
    }
  }

  // Fetch unarchive status
  const fetchUnarchivegStatus = async () => {
    const response = await Ajax.post('check_unarchive_progress')
    if (response.success) {
      let jobStauts = response.data
      setUnarchivePercentage(parseInt(jobStauts.progress))

      if ('processing' === jobStauts.status) {
        setTimeout(() => fetchUnarchivegStatus(), 1000)
      } else {
        setTimeout(() => {
          if ('completed' === jobStauts.status) {
            setStartBgUnarchiving('unarchive-complete')
          }
          setUnarchivePercentage(0)
          getArchivedOrder()
          checkDuplicateOrders()
        }, 2000)
      }
    }
  }

  // Check duplicate orders
  const checkDuplicateOrders = async () => {
    const response = await Ajax.post('check_duplicate_orders')
    if (response.success) {
      setDuplicateOrders(response.data)
      setBulkDuplicateModal(response.data.length)
    }
  }

  // Download exported file from database
  const downloadExportFile = () => {
    const a = document.createElement('a')
    a.href = exportDownloadUrl
    a.download = exportFileName + '.' + exportFormat || ''
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  }

  // Check Export background process
  const checkBgExportProcess = async () => {
    const response = await Ajax.post('check_bg_exporting')
    if (response.success) {
      if (response.data.is_bg_process) {
        setExportStatus('start-exporting')
        fetchExportingStatus()
      }
    }
  }

  // Check Unarchive background process
  const checkBgUnarchiveProcess = async () => {
    const response = await Ajax.post('check_bg_archiving')
    if (response.success) {
      if (response.data.is_bg_process) {
        setStartBgUnarchiving('start-unarchiving')
        fetchUnarchivegStatus()
      }
    }
  }

  // Flash door
  const flashDoor = () => {
    const popup = window.WPPOOL?.Popup('archive_master')
    if (!popup) return false
    popup.show()
  }

  // Handle view change (for navigation)
  const handleViewChange = (view) => {
    setActiveView(view)
  }

  // UseEffect hooks
  useEffect(() => {
    if (allowDplicateUnarchive) {
      if ('single' === unArchivingStatus) {
        proceedWithUnarchive(selectedOrders)
      }
    }
  }, [allowDplicateUnarchive])

  useEffect(() => {
    if ('single' === unArchivingStatus) {
      setSingleDuplicateCheckLoading(true)
      checkSingleDuplicateOrders(selectedOrders)
    }

    if ('bulk' === unArchivingStatus) {
      unarchiveAllOrder()
    }
  }, [unArchivingStatus])

  useEffect(() => {
    getArchivedOrder()
  }, [currentPage, ordersPerPage])

  useEffect(() => {
    checkBgExportProcess()
    checkBgUnarchiveProcess()
    checkDuplicateOrders()
    setIsPro(window.archm_admin?.is_pro || false)
    setSelectedDatabase(window.archm_admin?.archm_settings?.selected_database || '')
  }, [])

  // Context value with all states and functions
  const contextValue = {
    // States
    orders,
    setOrders,
    activeView,
    setActiveView,
    isPro,
    setIsPro,
    tableLoading,
    setTableLoading,
    selectAll,
    setSelectAll,
    bulkAction,
    setBulkAction,
    currentPage,
    setCurrentPage,
    totaOrderNumber,
    setTotaOrderNumber,
    modalLoading,
    setmodalLoading,
    isOpenUnarchiveModal,
    setIsOpenUnarchiveModal,
    isStartUnarchiveModal,
    setIsStartUnarchiveModal,
    startBgUnarchiving,
    setStartBgUnarchiving,
    modalTile,
    setmodalTile,
    modaDesc,
    setmodaDesc,
    ordersPerPage,
    setOrdersPerPage,
    singleOrderId,
    setSingleOrderId,
    exportLoading,
    setExportLoading,
    unArchivingStatus,
    setUnArchivingStatus,
    isUnarchiveCancelModal,
    setIsUnarchiveCancelModal,
    cancelUnarchiveBtnLoading,
    setCancelUnarchiveBtnLoading,
    unArchvedOrder,
    setUnarchvedOrder,
    totalUnArchvedOrder,
    setTotalUnArchvedOrder,
    isUnarchiveCancel,
    setIsUnarchiveCancel,
    selectedOrders,
    setSelectedOrders,
    allowDplicateUnarchive,
    setAllowDplicateUnarchive,
    percentage,
    setPercentage,
    unarchivePercentage,
    setUnarchivePercentage,
    exportStatus,
    setExportStatus,
    exportFileName,
    setExportFileName,
    exportFormat,
    setExportFormat,
    exportDownloadUrl,
    setExportDownloadUrl,
    exportSortType,
    setExportSortType,
    lastExportTime,
    setLastExportTime,
    isOpenExportModal,
    setIsOpenExportModal,
    isOpenExportCancelModal,
    setIsOpenExportCancelModal,
    cancelExportBtnLoading,
    setCancelExportBtnLoading,
    settingOffTooltip,
    setSettingOffTooltip,
    isEmptyOrderModal,
    setIsEmptyOrderModal,
    emptyOrderTitle,
    setEmptyOrderTitle,
    isOpenDeleteConfirmModal,
    setIsOpenDeleteConfirmModal,
    deleteLoading,
    setDeleteLoading,
    isOpenDuplicateModal,
    setIsOpenDuplicateModal,
    duplicateOrders,
    setDuplicateOrders,
    duplicateCheckLoading,
    setDuplicateCheckLoading,
    singleDuplicateCheckLoading,
    setSingleDuplicateCheckLoading,
    duplicatOrderText,
    setduplicatOrderText,
    isSyncModalOpen,
    setIsSyncModalOpen,
    syncLoading,
    setSyncLoading,
    selectedDatabase,
    setSelectedDatabase,
    ordserListTxt,
    setOrdserListTxt,
    searchQuery,
    setSearchQuery,
    filterStatus,
    setFilterStatus,
    filterDateRange,
    setFilterDateRange,
    dbConnected,
    setDbConnected,
    isSyncEmptyResult,
    setIsSyncEmptyResult,

    // Computed values
    totalPages,
    startIndex,

    // Functions
    handleSelectAll,
    handleSelectOrder,
    handleClearSearch,
    handleStatusFilterChange,
    handleDateFilterChange,
    isAnyFilterActive,
    handleClearFilter,
    handleApplyFilter,
    handleSearch,
    getSelectedOrder,
    checkSingleDuplicateOrders,
    proceedWithUnarchive,
    handleContinueUnarchive,
    handleCancelUnarchive,
    deleteDuplicateToSkip,
    handleDuplicateModal,
    handleStartUnarchiveModal,
    deleteOrder,
    setBulkDuplicateModal,
    performUnarchive,
    proceedBgUnArchiving,
    proceedDuplicateBgUnArchiving,
    singleOrderUnarchive,
    handleBulkAction,
    handlePermanentDelete,
    getArchivedOrder,
    handlePageChange,
    handleUnarchiveModal,
    handleUnarchiveCancelModal,
    handleIsOpenExportModal,
    handleIsEmptyOrderModal,
    handleSyncModal,
    handleSyncArchiveData,
    showBulkDuplicateModal,
    handleExportCancelModal,
    handelCancelExporting,
    handelCancelUnarchiving,
    exportOrder,
    unarchiveAllOrder,
    formateLastExportDate,
    fetchExportingStatus,
    fetchUnarchivegStatus,
    checkDuplicateOrders,
    downloadExportFile,
    checkBgExportProcess,
    checkBgUnarchiveProcess,
    flashDoor,
    handleViewChange,

    // Translation
    t
  }

  return (
    <ArchivedOrderContext.Provider value={contextValue}>
      {children}
    </ArchivedOrderContext.Provider>
  )
}

export const useArchivedOrder = () => {
  const context = useContext(ArchivedOrderContext)
  if (!context) {
    throw new Error('useArchivedOrder must be used within an ArchivedOrderProvider')
  }
  return context
}
