import { useState, useEffect } from 'react'
import { Link, useLocation } from 'react-router-dom'
import { Layout, Menu, Flex, Button } from 'antd'
import { DashboardOutlined, CaretDownFilled } from '@ant-design/icons'
import FilamentStockIcon from '../../Icons/FilamentStockIcon'
import PartStockIcon from '../../Icons/PartStockIcon'
import ProductStockIcon from '../../Icons/ProductStockIcon'
import StockAuditIcon from '../../Icons/StockAuditIcon'
import StockEventIcon from '../../Icons/StockEventIcon'
import CollapseSidebarIcon from '../../Icons/CollapseSidebarIcon'
import ExpandSidebarIcon from '../../Icons/ExpandSidebarIcon'
import { useMediaQuery } from 'react-responsive'

const { Sider } = Layout

const SIDEBAR_COLLAPSED_KEY = 'sidebar_collapsed'

const InventorySidebar = () => {
  const location = useLocation()
  const [selectedKey, setSelectedKey] = useState('inventory')
  const [collapsed, setCollapsed] = useState(() => {
    const savedState = sessionStorage.getItem(SIDEBAR_COLLAPSED_KEY)
    return savedState ? JSON.parse(savedState) : false
  })
  const isMobile = useMediaQuery({ maxWidth: 768 })

  useEffect(() => {
    const pathParts = location.pathname.split('/').filter(Boolean)
    if (pathParts.length > 2) {
      setSelectedKey(pathParts[2]) // Return the section (inventory/management)
    }
  }, [location.pathname])

  const handleCollapse = (newCollapsed) => {
    setCollapsed(newCollapsed)
    sessionStorage.setItem(SIDEBAR_COLLAPSED_KEY, JSON.stringify(newCollapsed))
  }

  const items = [
    {
      key: 'overview',
      label: <Link to='/dashboard/inventory/overview'>Overview</Link>,
      icon: <DashboardOutlined />
    },
    { type: 'divider' },
    {
      key: 'filamentstocks',
      label: (
        <Link to='/dashboard/inventory/filamentstocks'>Filament Stocks</Link>
      ),
      icon: <FilamentStockIcon />
    },
    {
      key: 'partstocks',
      label: <Link to='/dashboard/inventory/partstocks'>Part Stocks</Link>,
      icon: <PartStockIcon />
    },
    {
      key: 'productstocks',
      label: (
        <Link to='/dashboard/inventory/productstocks'>Product Stocks</Link>
      ),
      icon: <ProductStockIcon />
    },
    { type: 'divider' },
    {
      key: 'stockevents',
      label: <Link to='/dashboard/inventory/stockevents'>Stock Events</Link>,
      icon: <StockEventIcon />
    },
    {
      key: 'stockaudits',
      label: <Link to='/dashboard/inventory/stockaudits'>Stock Audits</Link>,
      icon: <StockAuditIcon />
    }
  ]

  if (isMobile) {
    return (
      <Menu
        mode='horizontal'
        selectedKeys={[selectedKey]}
        defaultSelectedKeys={['overview']}
        items={items}
        style={{ width: '100%' }}
        _internalDisableMenuItemTitleTooltip
        overflowedIndicator={<Button type='text' icon={<CaretDownFilled />} />}
      />
    )
  }

  return (
    <Sider width={250} theme='light' collapsed={collapsed}>
      <Flex
        style={{ height: '100%' }}
        vertical
        className='ant-menu-root ant-menu-inline ant-menu-light'
      >
        <Menu
          mode='inline'
          selectedKeys={[selectedKey]}
          defaultSelectedKeys={['overview']}
          style={{ height: '100%', flexGrow: 1, border: 'none' }}
          items={items}
          _internalDisableMenuItemTitleTooltip
        />
        <Flex style={{ padding: '4px', width: '100%' }}>
          <Button
            size='large'
            type='text'
            icon={collapsed ? <ExpandSidebarIcon /> : <CollapseSidebarIcon />}
            style={{ flexGrow: 1 }}
            onClick={() => handleCollapse(!collapsed)}
          />
        </Flex>
      </Flex>
    </Sider>
  )
}

export default InventorySidebar
