// DashboardNavigation.js
import React, { useContext, useEffect, useState } from 'react'
import {
  Menu,
  Flex,
  Tag,
  Space,
  Dropdown,
  Button,
  Tooltip,
  Typography,
  Divider,
  Badge
} from 'antd'
import {
  LogoutOutlined,
  MailOutlined,
  MenuOutlined,
  LoadingOutlined
} from '@ant-design/icons'
import { AuthContext } from '../context/AuthContext'
import { SocketContext } from '../context/SocketContext'
import { SpotlightContext } from '../context/SpotlightContext'
import { NotificationContext } from '../context/NotificationContext'
import { useNavigate, useLocation } from 'react-router-dom'
import { Header } from 'antd/es/layout/layout'
import { useMediaQuery } from 'react-responsive'

import FarmControlLogo from '../../Logos/FarmControlLogo'
import FarmControlLogoSmall from '../../Logos/FarmControlLogoSmall'
import ProductionIcon from '../../Icons/ProductionIcon'
import InventoryIcon from '../../Icons/InventoryIcon'
import PersonIcon from '../../Icons/PersonIcon'
import CloudIcon from '../../Icons/CloudIcon'
import BellIcon from '../../Icons/BellIcon'
import SearchIcon from '../../Icons/SearchIcon'
import SettingsIcon from '../../Icons/SettingsIcon'
import DeveloperIcon from '../../Icons/DeveloperIcon'

const { Text } = Typography

const DashboardNavigation = () => {
  const { logout, userProfile } = useContext(AuthContext)
  const { showSpotlight } = useContext(SpotlightContext)
  const { toggleNotificationCenter, unreadCount } =
    useContext(NotificationContext)
  const { socket } = useContext(SocketContext)
  const [socketState, setSocketState] = useState('disconnected')
  const navigate = useNavigate()
  const location = useLocation()
  const [selectedKey, setSelectedKey] = useState('production')
  const isMobile = useMediaQuery({ maxWidth: 768 })

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

  useEffect(() => {
    if (socket?.connecting) {
      setSocketState('connecting')
    } else if (socket?.connected) {
      setSocketState('connected')
    } else {
      setSocketState('disconnected')
    }
  }, [socket?.connecting, socket?.connected])

  const mainMenuItems = [
    {
      key: 'production',
      label: 'Production',
      icon: <ProductionIcon />
    },
    {
      key: 'inventory',
      label: 'Inventory',
      icon: <InventoryIcon />
    },
    {
      key: 'management',
      label: 'Management',
      icon: <SettingsIcon />
    }
  ]

  const userMenuItems = {
    items: [
      {
        key: 'username',
        label: userProfile?.username,
        icon: <PersonIcon />,
        disabled: true
      },
      {
        key: 'email',
        label: userProfile?.email,
        icon: <MailOutlined />,
        disabled: true
      },
      {
        key: 'logout',
        label: 'Logout',
        icon: <LogoutOutlined />
      }
    ],
    onClick: (key) => {
      if (key === 'profile') {
        navigate('/profile')
      } else if (key === 'logout') {
        logout()
      }
    }
  }

  const handleMainMenuClick = ({ key }) => {
    if (key === 'production') {
      navigate('/dashboard/production/overview')
    } else if (key === 'inventory') {
      navigate('/dashboard/inventory/filamentstocks')
    } else if (key === 'management') {
      navigate('/dashboard/management/filaments')
    }
  }

  return (
    <Header
      style={{
        width: '100vw',
        padding: 0,
        marginBottom: '0.1px',
        background: 'unset'
      }}
      theme='light'
      className='ant-menu-horizontal'
    >
      <Flex
        gap={'large'}
        align='center'
        className='ant-menu-light'
        style={{
          padding: '0 26px',
          height: '100%',
          borderBottom: '1px solid rgba(5, 5, 5, 0.00)'
        }}
      >
        {!isMobile ? (
          <FarmControlLogo style={{ fontSize: '200px' }} />
        ) : (
          <FarmControlLogoSmall style={{ fontSize: '48px' }} />
        )}
        <Menu
          mode='horizontal'
          items={mainMenuItems}
          style={{
            flexWrap: 'wrap',
            flexGrow: 1,
            border: 0
          }}
          onClick={handleMainMenuClick}
          selectedKeys={[selectedKey]}
          overflowedIndicator={<Button type='text' icon={<MenuOutlined />} />}
        />
        <Flex gap={'middle'} align='center'>
          <Space>
            <Tooltip title={<Text keyboard>⌘ ⇧ P</Text>} arrow={false}>
              <Button
                icon={<SearchIcon />}
                type='text'
                style={{ marginTop: '2px' }}
                onClick={() => showSpotlight()}
              ></Button>
            </Tooltip>
            <Badge count={unreadCount} size='small'>
              <Button
                icon={<BellIcon />}
                type='text'
                style={{ marginTop: '2px' }}
                onClick={toggleNotificationCenter}
              ></Button>
            </Badge>
          </Space>
          <Space>
            {socketState === 'connected' ? (
              <Tooltip title='Connected to server' arrow={false}>
                <Tag
                  color='success'
                  style={{ marginRight: 0 }}
                  icon={<CloudIcon />}
                />
              </Tooltip>
            ) : null}
            {socketState === 'connecting' ? (
              <Tooltip title='Connecting to server...' arrow={false}>
                <Tag
                  color='default'
                  style={{ marginRight: 0 }}
                  icon={<LoadingOutlined />}
                />
              </Tooltip>
            ) : null}
            {socketState === 'disconnected' ? (
              <Tooltip title='Disconnected from server' arrow={false}>
                <Tag
                  color='error'
                  style={{ marginRight: 0 }}
                  icon={<CloudIcon />}
                />
              </Tooltip>
            ) : null}
          </Space>
          {process.env.NODE_ENV === 'development' && (
            <Space>
              <Tooltip title='Developer' arrow={false}>
                <Tag
                  color='yellow'
                  style={{ marginRight: 0 }}
                  icon={<DeveloperIcon />}
                  onClick={() => {
                    navigate('/dashboard/developer/sessionstorage')
                  }}
                />
              </Tooltip>
            </Space>
          )}
          {userProfile ? (
            <Space>
              <Dropdown menu={userMenuItems} placement='bottomRight'>
                <Tag style={{ marginRight: 0 }} icon={<PersonIcon />}>
                  {!isMobile && (userProfile?.name || userProfile.username)}
                </Tag>
              </Dropdown>
            </Space>
          ) : null}
        </Flex>
      </Flex>
      <Divider style={{ margin: 0 }} />
    </Header>
  )
}

export default DashboardNavigation
