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

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'
import PrinterIcon from '../../Icons/PrinterIcon'
import { ElectronContext } from '../context/ElectronContext'
import DashboardWindowButtons from './DashboardWindowButtons'

const DashboardNavigation = () => {
  const { logout, userProfile } = useContext(AuthContext)
  const { showSpotlight } = useContext(SpotlightContext)
  const { toggleNotificationCenter, unreadCount } = useContext(ApiServerContext)
  const { printServer } = useContext(PrintServerContext)
  const { apiServer } = useContext(ApiServerContext)
  const [printServerState, setPrintServerState] = useState('disconnected')
  const [apiServerState, setApiServerState] = useState('disconnected')
  const navigate = useNavigate()
  const location = useLocation()
  const [selectedKey, setSelectedKey] = useState('production')
  const isMobile = useMediaQuery({ maxWidth: 768 })
  const { platform, isElectron } = useContext(ElectronContext)

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

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

  useEffect(() => {
    if (apiServer?.connecting) {
      setApiServerState('connecting')
    } else if (apiServer?.connected) {
      setApiServerState('connected')
    } else {
      setApiServerState('disconnected')
    }
  }, [apiServer?.connecting, apiServer?.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')
    }
  }

  const navigationContents = (
    <>
      {isElectron && platform == 'darwin' ? <DashboardWindowButtons /> : null}
      {!isElectron && !isMobile ? (
        <FarmControlLogo style={{ fontSize: '200px' }} />
      ) : !isElectron && isMobile ? (
        <FarmControlLogoSmall style={{ fontSize: '48px' }} />
      ) : null}
      <Menu
        mode='horizontal'
        className={isElectron ? 'electron-navigation' : null}
        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>
          <KeyboardShortcut
            shortcut='alt+q'
            hint='ALT Q'
            onTrigger={() => showSpotlight()}
          >
            <Button
              icon={<SearchIcon />}
              type='text'
              style={{ marginTop: '2px' }}
              onClick={() => showSpotlight()}
            />
          </KeyboardShortcut>
          <Badge count={unreadCount} size='small'>
            <KeyboardShortcut
              shortcut='alt+n'
              hint='ALT N'
              onTrigger={() => toggleNotificationCenter()}
            >
              <Button
                icon={<BellIcon />}
                type='text'
                style={{ marginTop: '2px' }}
                onClick={() => toggleNotificationCenter()}
              />
            </KeyboardShortcut>
          </Badge>
        </Space>

        {process.env.NODE_ENV === 'development' && (
          <Space>
            {printServerState === 'connected' ? (
              <Tooltip title='Connected to print server' arrow={false}>
                <Tag
                  color='success'
                  style={{ marginRight: 0 }}
                  icon={<PrinterIcon />}
                />
              </Tooltip>
            ) : null}
            {printServerState === 'connecting' ? (
              <Tooltip title='Connecting to print erver...' arrow={false}>
                <Tag
                  color='default'
                  style={{ marginRight: 0 }}
                  icon={<LoadingOutlined />}
                />
              </Tooltip>
            ) : null}
            {printServerState === 'disconnected' ? (
              <Tooltip title='Disconnected from print server' arrow={false}>
                <Tag
                  color='error'
                  style={{ marginRight: 0 }}
                  icon={<PrinterIcon />}
                />
              </Tooltip>
            ) : null}
            {apiServerState === 'connected' ? (
              <Tooltip title='Connected to api server' arrow={false}>
                <Tag
                  color='success'
                  style={{ marginRight: 0 }}
                  icon={<CloudIcon />}
                />
              </Tooltip>
            ) : null}
            {apiServerState === 'connecting' ? (
              <Tooltip title='Connecting to api erver...' arrow={false}>
                <Tag
                  color='default'
                  style={{ marginRight: 0 }}
                  icon={<LoadingOutlined />}
                />
              </Tooltip>
            ) : null}
            {apiServerState === 'disconnected' ? (
              <Tooltip title='Disconnected from api server' arrow={false}>
                <Tag
                  color='error'
                  style={{ marginRight: 0 }}
                  icon={<CloudIcon />}
                />
              </Tooltip>
            ) : null}
            <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>
    </>
  )

  return (
    <>
      {isElectron ? (
        <Flex
          className='ant-menu-horizontal ant-menu-light electron-navigation-wrapper'
          style={{ lineHeight: '40px', padding: '0 8px 0 4px' }}
        >
          {navigationContents}
        </Flex>
      ) : (
        <Flex vertical>
          <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)'
              }}
            >
              {navigationContents}
            </Flex>
            <Divider style={{ margin: 0 }} />
          </Header>
        </Flex>
      )}
    </>
  )
}

export default DashboardNavigation
