import productionSidebarItems from './sidebars/production'
import inventorySidebarItems from './sidebars/inventory'
import salesSidebarItems from './sidebars/sales'
import financeSidebarItems from './sidebars/finance'
import managementSidebarItems from './sidebars/management'
import developerSidebarItems from './sidebars/developer'

const SIDEBARS = {
  production: {
    key: 'production',
    label: 'Production',
    iconKey: 'production',
    items: productionSidebarItems
  },
  inventory: {
    key: 'inventory',
    label: 'Inventory',
    iconKey: 'inventory',
    items: inventorySidebarItems
  },
  sales: {
    key: 'sales',
    label: 'Sales',
    iconKey: 'sales',
    items: salesSidebarItems,
    routeAliases: {
      '/dashboard/sales/listingvarients': 'listings'
    }
  },
  finance: {
    key: 'finance',
    label: 'Finance',
    iconKey: 'finance',
    items: financeSidebarItems
  },
  management: {
    key: 'management',
    label: 'Management',
    iconKey: 'settings',
    items: managementSidebarItems
  },
  developer: {
    key: 'developer',
    label: 'Developer',
    iconKey: 'developer',
    items: developerSidebarItems
  }
}

const splitPath = (path) => path.split('/').filter(Boolean)

const isPathPrefixMatch = (candidatePath, pathname) => {
  const candidateParts = splitPath(candidatePath)
  const pathParts = splitPath(pathname)
  if (candidateParts.length > pathParts.length) return false
  for (let i = 0; i < candidateParts.length; i++) {
    if (candidateParts[i] !== pathParts[i]) return false
  }
  return true
}

const getFilteredItems = (items = [], includeDev = false) =>
  items
    .filter((item) => item?.devOnly !== true || includeDev)
    .map((item) => {
      if (item?.children && Array.isArray(item.children)) {
        return { ...item, children: getFilteredItems(item.children, includeDev) }
      }
      return { ...item }
    })

const flattenPathEntries = (items = [], acc = []) => {
  items.forEach((item) => {
    if (item?.type === 'divider') return
    if (item?.path) {
      acc.push({ path: item.path, key: item.key })
    }
    if (item?.children && Array.isArray(item.children)) {
      flattenPathEntries(item.children, acc)
    }
  })
  return acc
}

const findDefaultKey = (items = []) => {
  for (const item of items) {
    if (item?.type === 'divider') continue
    if (item?.children && item.children.length > 0) {
      const childKey = findDefaultKey(item.children)
      if (childKey) return childKey
    }
    if (item?.key) return item.key
  }
  return ''
}

const toMenuItems = (items = []) =>
  items.map((item) => {
    if (item?.type === 'divider') return { type: 'divider' }

    const menuItem = {
      key: item.key,
      label: item.label,
      iconKey: item.iconKey
    }

    if (item?.path) {
      menuItem.path = item.path
    }

    if (item?.children && Array.isArray(item.children)) {
      menuItem.children = toMenuItems(item.children)
    }

    return menuItem
  })

export const getSidebar = (sidebarKey) => SIDEBARS[sidebarKey] || null

export const getSidebarItems = (sidebarKey, options = {}) => {
  const sidebar = getSidebar(sidebarKey)
  if (!sidebar) return []
  const { includeDev = false } = options
  return getFilteredItems(sidebar.items, includeDev)
}

export const getSidebarSelectedKey = (sidebarKey, pathname, options = {}) => {
  const sidebar = getSidebar(sidebarKey)
  if (!sidebar) return ''

  const items = getSidebarItems(sidebarKey, options)
  const pathEntries = flattenPathEntries(items)
  const aliasEntries = Object.entries(sidebar.routeAliases || {}).map(
    ([path, key]) => ({ path, key })
  )

  const match = [...pathEntries, ...aliasEntries]
    .filter((entry) => isPathPrefixMatch(entry.path, pathname))
    .sort((a, b) => splitPath(b.path).length - splitPath(a.path).length)[0]

  return match?.key || findDefaultKey(items)
}

export const getSidebarMenuSections = (options = {}) => {
  const { includeDev = false } = options
  return Object.values(SIDEBARS)
    .filter((sidebar) => includeDev || sidebar.key !== 'developer')
    .map((sidebar) => ({
      key: sidebar.key,
      label: sidebar.label,
      iconKey: sidebar.iconKey,
      items: toMenuItems(getSidebarItems(sidebar.key, { includeDev }))
    }))
}

export const getSidebarDefaultPath = (sidebarKey, options = {}) => {
  const items = getSidebarItems(sidebarKey, options)
  const first = flattenPathEntries(items)[0]
  return first?.path || '/dashboard/production/overview'
}
