// DashboardBreadcrumb.js
import { Breadcrumb, Button, Flex, Space } from 'antd'
import { Link, useLocation, useNavigate } from 'react-router-dom'
import ArrowLeftIcon from '../../Icons/ArrowLeftIcon'
import ArrowRightIcon from '../../Icons/ArrowRightIcon'
import { getModelByName } from '../../../database/ObjectModels'

const breadcrumbNameMap = {
  production: 'Production',
  inventory: 'Inventory',
  management: 'Management',
  developer: 'Developer',
  overview: 'Overview',
  info: 'Info',
  design: 'Design',
  control: 'Control'
}

const mainSections = ['production', 'inventory', 'management', 'developer']

const DashboardBreadcrumb = () => {
  const location = useLocation()
  const navigate = useNavigate()
  const pathSnippets = location.pathname.split('/').filter((i) => i)

  function segmentToModel(segment) {
    if (segment) {
      // If segment ends with 's', remove it and get the model
      if (segment.endsWith('s')) {
        const singularSegment = segment.slice(0, -1)
        return getModelByName(singularSegment, true)
      }
      // Otherwise, get the model as is
      return getModelByName(segment, true)
    }
    return null
  }

  const breadcrumbItems = pathSnippets.map((segment, index) => {
    const url = `/${pathSnippets.slice(0, index + 1).join('/')}`
    if (segment !== 'dashboard') {
      const isMainSection = mainSections.includes(segment)
      const model = segmentToModel(segment)
      const modelLabelPlural = model?.label ? `${model.label}s` : null
      const name = breadcrumbNameMap[segment] || modelLabelPlural || segment
      if (isMainSection) {
        return {
          title: (
            <span style={{ padding: '0 12px' }} key={segment}>
              {name}
            </span>
          ),
          key: segment
        }
      }

      return {
        title: (
          <Link to={url} style={{ padding: '0 12px' }}>
            {name}
          </Link>
        ),
        key: url
      }
    } else {
      return {}
    }
  })

  return (
    <Flex align='center' gap={'small'}>
      <Flex gap={'small'}>
        <Space.Compact>
          <Button
            type='text'
            icon={<ArrowLeftIcon style={{ fontSize: '14px' }} />}
            onClick={() => navigate(-1)}
            style={{ padding: '0 2px', height: '22px' }}
          />
          <Button
            type='text'
            icon={<ArrowRightIcon style={{ fontSize: '14px' }} />}
            onClick={() => navigate(1)}
            style={{ padding: '0 2px', height: '22px' }}
          />
        </Space.Compact>
      </Flex>
      <Breadcrumb items={breadcrumbItems} />
    </Flex>
  )
}

export default DashboardBreadcrumb
