import { useState, useEffect } from 'react'
import { Link, useLocation } from 'react-router-dom'
import { Layout, Menu, Flex, Button } from 'antd'
import { CaretDownFilled } from '@ant-design/icons'
import FilamentIcon from '../../Icons/FilamentIcon'
import PartIcon from '../../Icons/PartIcon'
import ProductIcon from '../../Icons/ProductIcon'
import VendorIcon from '../../Icons/VendorIcon'
import MaterialIcon from '../../Icons/MaterialIcon'
import CollapseSidebarIcon from '../../Icons/CollapseSidebarIcon'
import ExpandSidebarIcon from '../../Icons/ExpandSidebarIcon'
import AuditLogIcon from '../../Icons/AuditLogIcon'
import NoteTypeIcon from '../../Icons/NoteTypeIcon'
import { useMediaQuery } from 'react-responsive'
import SettingsIcon from '../../Icons/SettingsIcon'

const { Sider } = Layout

const SIDEBAR_COLLAPSED_KEY = 'sidebar_collapsed'

const ManagementSidebar = () => {
  const location = useLocation()
  const [selectedKey, setSelectedKey] = useState('production')
  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 (production/management)
    }
  }, [location.pathname])

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

  const items = [
    {
      key: 'filaments',
      label: <Link to='/dashboard/management/filaments'>Filaments</Link>,
      icon: <FilamentIcon />
    },
    {
      key: 'parts',
      label: <Link to='/dashboard/management/parts'>Parts</Link>,
      icon: <PartIcon />
    },
    {
      key: 'products',
      label: <Link to='/dashboard/management/products'>Products</Link>,
      icon: <ProductIcon />
    },
    {
      key: 'vendors',
      label: <Link to='/dashboard/management/vendors'>Vendors</Link>,
      icon: <VendorIcon />
    },
    {
      key: 'materials',
      label: <Link to='/dashboard/management/materials'>Materials</Link>,
      icon: <MaterialIcon />
    },
    {
      key: 'notetypes',
      label: <Link to='/dashboard/management/notetypes'>Note Types</Link>,
      icon: <NoteTypeIcon />
    },
    { type: 'divider' },
    {
      key: 'settings',
      label: <Link to='/dashboard/management/settings'>Settings</Link>,
      icon: <SettingsIcon />
    },
    {
      key: 'auditlogs',
      label: <Link to='/dashboard/management/auditlogs'>Audit Log</Link>,
      icon: <AuditLogIcon />
    }
  ]

  if (isMobile) {
    return (
      <Menu
        mode='horizontal'
        selectedKeys={[selectedKey]}
        defaultSelectedKeys={['filaments']}
        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={['filaments']}
          items={items}
          _internalDisableMenuItemTitleTooltip
          style={{ flexGrow: 1, border: 'none' }}
        />
        <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 ManagementSidebar
