'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import Image from 'next/image'
import { motion, AnimatePresence } from 'framer-motion'
import { menuApi, MenuItem } from '@/lib/api'
import { Menu, X, ChevronDown, AlertCircle, Search, Bell } from 'lucide-react'
import { newsTickerApi } from '@/lib/api'
import SearchDialog from './SearchDialog'

// Fallback menu when API is unavailable
const fallbackMenu: MenuItem[] = [
  {
    _id: '1',
    title: 'About Us',
    slug: 'about',
    url: '/about',
    order: 0,
  },
  {
    _id: '2',
    title: 'Services',
    slug: 'services',
    order: 1,
    children: [
      { _id: '2-1', title: 'Accounts', slug: 'accounts', url: '/services/accounts', order: 0 },
      { _id: '2-2', title: 'Building Plans', slug: 'building-plans', url: '/services/building-plans', order: 1 },
      { _id: '2-3', title: 'Cemetery & Hall', slug: 'cemetery-hall', url: '/services/cemetery-hall', order: 2 },
      { _id: '2-4', title: 'Electricity', slug: 'electricity', url: '/services/electricity', order: 3 },
      { _id: '2-5', title: 'Fire and Disaster Services', slug: 'fire-disaster-services', url: '/services/fire-disaster-services', order: 4 },
      { _id: '2-6', title: 'Housing', slug: 'housing', url: '/services/housing', order: 5 },
      { _id: '2-7', title: 'Refuse Collection', slug: 'refuse-collection', url: '/services/refuse-collection', order: 6 },
      { _id: '2-8', title: 'Traffic', slug: 'traffic', url: '/services/traffic', order: 7 },
      { _id: '2-9', title: 'Transport, Roads and Robots', slug: 'transport-roads-robots', url: '/services/transport-roads-robots', order: 8 },
      { _id: '2-10', title: 'Water & Sanitation Services', slug: 'water-sanitation-services', url: '/services/water-sanitation-services', order: 9 },
      { _id: '2-11', title: 'Documents', slug: 'documents', order: 10 },
    ],
  },
  {
    _id: '3',
    title: 'Council',
    slug: 'council',
    order: 2,
    children: [
      { _id: '3-1', title: 'Executive Mayor', slug: 'executive-mayor', url: '/council/executive-mayor', order: 0 },
      { _id: '3-2', title: 'Municipal Council', slug: 'municipal-council', url: '/council/municipal-council', order: 1 },
      { _id: '3-3', title: 'Office of the single Whip', slug: 'office-single-whip', url: '/council/office-single-whip', order: 2 },
      { _id: '3-4', title: 'Members of the Mayoral Committee', slug: 'members-mayoral-committee', url: '/council/members-mayoral-committee', order: 3 },
      { _id: '3-5', title: 'MPAC', slug: 'mpac', url: '/council/mpac', order: 4 },
      { _id: '3-6', title: 'Speaker of Council', slug: 'speaker-council', url: '/council/speaker-council', order: 5 },
      { _id: '3-7', title: 'Ward Committees', slug: 'ward-committees', url: '/council/ward-committees', order: 6 },
    ],
  },
  {
    _id: '4',
    title: 'Directorates',
    slug: 'directorates',
    order: 3,
    children: [
      { _id: '4-1', title: 'Budget & Treasury Office', slug: 'budget-treasury-office', order: 0 },
      { _id: '4-2', title: 'Community Development', slug: 'community-development', order: 1 },
      { _id: '4-3', title: 'Corporate Support Services', slug: 'corporate-support-services', order: 2 },
      { _id: '4-4', title: 'Economic Development & Planning', slug: 'economic-development-planning', order: 3 },
      { _id: '4-5', title: 'Human Settlements & Planning', slug: 'human-settlements-planning', order: 4 },
      { _id: '4-6', title: 'IDP, PMS and Legal Services', slug: 'idp-pms-legal-services', order: 5 },
      { _id: '4-7', title: 'Infrastructure and Technical Services', slug: 'infrastructure-technical-services', order: 6 },
      { _id: '4-8', title: 'Office of the Municipal Manager', slug: 'office-municipal-manager', order: 7 },
      { _id: '4-9', title: 'Public Safety, Fleet and Facilities Management', slug: 'public-safety-fleet-facilities', order: 8 },
    ],
  },
  {
    _id: '5',
    title: 'Tenders',
    slug: 'tenders',
    order: 4,
    children: [
      { _id: '5-1', title: 'Tenders', slug: 'tenders', url: '/tenders', order: 0 },
      { _id: '5-2', title: 'Tenders Awarded', slug: 'tenders-awarded', url: '/tenders/tenders-awarded', order: 1 },
      { _id: '5-3', title: 'Vendor Registration', slug: 'vendor-registration', url: '/tenders/vendor-registration', order: 2 },
      { _id: '5-4', title: 'Request For Quotations', slug: 'request-quotations', url: '/tenders/request-quotations', order: 3 },
    ],
  },
  {
    _id: '6',
    title: 'Vacancies',
    slug: 'vacancies',
    order: 5,
    children: [
      { _id: '6-1', title: 'Vacancies', slug: 'vacancies', url: '/vacancies', order: 0 },
      { _id: '6-2', title: 'Forms', slug: 'forms', url: '/vacancies/forms', order: 1 },
    ],
  },
  {
    _id: '7',
    title: 'News',
    slug: 'news',
    url: '/news',
    order: 6,
  },
  {
    _id: '8',
    title: 'Contact Us',
    slug: 'contact',
    url: '/contact',
    order: 8,
  },
]

export default function Navigation() {
  const [menuItems, setMenuItems] = useState<MenuItem[]>(fallbackMenu)
  const [isOpen, setIsOpen] = useState(false)
  const [activeSubmenu, setActiveSubmenu] = useState<string | null>(null)
  const [isScrolled, setIsScrolled] = useState(false)
  const [isVisible, setIsVisible] = useState(true)
  const [lastScrollY, setLastScrollY] = useState(0)
  const [newsTickerCount, setNewsTickerCount] = useState(0)
  const [isSearchOpen, setIsSearchOpen] = useState(false)
  
  // Check if menu animation has been played in this session
  const [hasAnimated, setHasAnimated] = useState(() => {
    if (typeof window !== 'undefined') {
      return sessionStorage.getItem('menuAnimated') === 'true'
    }
    return false
  })

  useEffect(() => {
    const fetchMenu = async () => {
      try {
        const items = await menuApi.getAll()
        if (items && items.length > 0) {
          // Normalize legacy/incorrect links (e.g. About Us accidentally pointing to '/')
          const normalized = items.map((it) => {
            if ((it.slug === 'about' || it.title === 'About Us') && it.url === '/') {
              return { ...it, url: '/about' }
            }
            return it
          })
          setMenuItems(normalized)
        }
      } catch (error) {
        console.error('Error fetching menu:', error)
        // Keep using fallback menu
      }
    }

    const fetchNewsTickerCount = async () => {
      try {
        const items = await newsTickerApi.getAll()
        // API already returns only active items, so just count them
        setNewsTickerCount(items.length)
      } catch (error) {
        console.error('Error fetching news ticker count:', error)
        setNewsTickerCount(0)
      }
    }

    // Mark animation as played after first render
    if (!hasAnimated && typeof window !== 'undefined') {
      // Use a small delay to ensure animation starts
      setTimeout(() => {
        sessionStorage.setItem('menuAnimated', 'true')
        setHasAnimated(true)
      }, 100)
    }

    fetchMenu()
    fetchNewsTickerCount()

    // Refresh news ticker count every 30 seconds
    const interval = setInterval(fetchNewsTickerCount, 30000)
    return () => clearInterval(interval)

    const handleScroll = () => {
      const currentScrollY = window.scrollY
      
      setIsScrolled(currentScrollY > 20)
      
      // Fade out when scrolling down, fade in when scrolling up
      if (currentScrollY > lastScrollY && currentScrollY > 100) {
        // Scrolling down
        setIsVisible(false)
      } else {
        // Scrolling up
        setIsVisible(true)
      }
      
      setLastScrollY(currentScrollY)
    }
    
    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
  }, [lastScrollY])

  const toggleSubmenu = (itemId: string) => {
    setActiveSubmenu(activeSubmenu === itemId ? null : itemId)
  }

  return (
    <nav className={`sticky top-0 w-full z-50 transition-all duration-300 py-2 ${
      isVisible ? 'opacity-100' : 'opacity-0 pointer-events-none'
    }`}>
      <div className="px-4 mx-auto max-w-[1920px]">
        <div className={`rounded-full transition-all duration-300 ${
          isScrolled
            ? 'glass-dark shadow-lg'
            : 'bg-primary/20 backdrop-blur-md'
        }`}>
          <div className="px-4">
            <div className="flex items-center justify-center h-20 relative">
          {/* Logo */}
          <Link href="/home" className="absolute left-0 flex items-center space-x-2 z-50 flex-shrink-0">
            <div className="relative w-20 h-20">
              <Image
                src="/logo.png"
                alt="Madibeng Local Municipality Logo"
                fill
                className="object-contain"
                priority
              />
            </div>
            <div className="text-white text-xs font-semibold leading-tight text-center">
              <div>Madibeng</div>
              <div>Local</div>
              <div>Municipality</div>
            </div>
          </Link>

          {/* Desktop Menu */}
          <div className="hidden lg:flex items-center space-x-1 relative">
            {menuItems.map((item, index) => {
              // Curved path: start bottom-right, curve up, then horizontal
              // Keyframes create the curved path effect
              return (
                <motion.div
                  key={item._id}
                  className="relative group"
                  initial={hasAnimated ? { 
                    x: 0,
                    y: 0,
                    opacity: 1
                  } : { 
                    x: 400,
                    y: 300,
                    opacity: 0
                  }}
                  animate={hasAnimated ? { 
                    x: 0,
                    y: 0,
                    opacity: 1
                  } : { 
                    x: [400, 400, 200, 0],
                    y: [300, 100, 50, 0],
                    opacity: [0, 0, 0.5, 1]
                  }}
                  transition={hasAnimated ? {
                    duration: 0
                  } : {
                    duration: 3,
                    delay: index * 0.24,
                    times: [0, 0.4, 0.7, 1],
                    ease: [0.25, 0.46, 0.45, 0.94]
                  }}
                  onMouseEnter={() => item.children && setActiveSubmenu(item._id)}
                  onMouseLeave={() => setActiveSubmenu(null)}
                >
                  <Link
                    href={item.url || `/${item.slug}`}
                    className="flex items-center space-x-1 px-2 py-2 text-white rounded-full hover:bg-secondary/40 transition-all duration-200 font-medium text-lg hover:scale-[1.2]"
                  >
                    <span>{item.title}</span>
                    {item.children && item.children.length > 0 && (
                      <ChevronDown className="w-4 h-4" />
                    )}
                  </Link>

                  {/* Submenu */}
                  <AnimatePresence>
                    {item.children && item.children.length > 0 && activeSubmenu === item._id && (
                      <motion.div
                        initial={{ opacity: 0, y: -10 }}
                        animate={{ opacity: 1, y: 0 }}
                        exit={{ opacity: 0, y: -10 }}
                        transition={{ duration: 0.2 }}
                        className="absolute top-full left-0 mt-2 w-64 glass-submenu rounded-lg shadow-xl overflow-hidden"
                      >
                        {item.children.map((child, childIndex) => (
                          <motion.div
                            key={child._id}
                            initial={{ opacity: 0, x: -20 }}
                            animate={{ opacity: 1, x: 0 }}
                            exit={{ opacity: 0, x: -20 }}
                            transition={{ 
                              duration: 0.3, 
                              delay: childIndex * 0.05,
                              ease: 'easeOut'
                            }}
                          >
                            <Link
                              href={child.url || `/${child.slug}`}
                              className="block px-4 py-3 text-white hover:bg-white/20 transition-colors duration-200 border-b border-white/10 last:border-0"
                            >
                              {child.title}
                            </Link>
                          </motion.div>
                        ))}
                      </motion.div>
                    )}
                  </AnimatePresence>
                </motion.div>
              )
            })}
          </div>

          {/* Right Side Actions - Desktop */}
          <div className="hidden lg:flex absolute right-0 items-center gap-3 z-50">
            {/* News Ticker Bell Icon */}
            <Link
              href="/public-notice"
              className="relative flex items-center justify-center w-10 h-10 bg-tertiary/80 hover:bg-tertiary text-white rounded-full shadow-lg transition-all duration-300"
              title="Public Notices"
            >
              <motion.div
                animate={{ 
                  rotate: [-15, 15, -15],
                }}
                transition={{ 
                  duration: 1.5,
                  repeat: Infinity,
                  ease: "easeInOut"
                }}
                style={{ transformOrigin: 'top center' }}
              >
                <Bell className="w-5 h-5" fill="#ea580c" />
              </motion.div>
              {newsTickerCount > 0 && (
                <span className="absolute -top-1 -right-1 flex items-center justify-center min-w-[20px] h-5 px-1.5 bg-red-500 text-white text-xs font-bold rounded-full border-2 border-white z-[60] shadow-lg">
                  {newsTickerCount > 99 ? '99+' : newsTickerCount}
                </span>
              )}
            </Link>

            {/* Search Button */}
            <button
              onClick={() => setIsSearchOpen(true)}
              className="flex items-center gap-2 bg-secondary/80 hover:bg-secondary text-white px-4 py-2 rounded-full shadow-lg transition-all duration-300"
            >
              <Search size={20} />
              <span className="font-semibold text-sm">Search</span>
            </button>

            {/* Submit a Complaint Button */}
            <Link
              href="/complaints"
              className="flex items-center gap-2 bg-[#FF5722] hover:bg-[#E64A19] text-white px-4 py-2 rounded-full shadow-lg transition-all duration-300"
            >
              <AlertCircle size={20} />
              <span className="font-semibold text-sm">Submit a Complaint</span>
            </Link>
          </div>

          {/* Right Side Actions - Mobile */}
          <div className="lg:hidden absolute right-12 flex items-center gap-2 z-50">
            {/* News Ticker Bell Icon */}
            <Link
              href="/public-notice"
              className="relative flex items-center justify-center w-9 h-9 bg-tertiary/80 hover:bg-tertiary text-white rounded-full shadow-lg transition-all duration-300"
              title="Public Notices"
            >
              <motion.div
                animate={{ 
                  rotate: [-15, 15, -15],
                }}
                transition={{ 
                  duration: 1.5,
                  repeat: Infinity,
                  ease: "easeInOut"
                }}
                style={{ transformOrigin: 'top center' }}
              >
                <Bell className="w-4 h-4" fill="#ea580c" />
              </motion.div>
              {newsTickerCount > 0 && (
                <span className="absolute -top-1 -right-1 flex items-center justify-center min-w-[18px] h-[18px] px-1 bg-red-500 text-white text-[10px] font-bold rounded-full border-2 border-white z-[60] shadow-lg">
                  {newsTickerCount > 99 ? '99+' : newsTickerCount}
                </span>
              )}
            </Link>

            {/* Search Button */}
            <button
              onClick={() => setIsSearchOpen(true)}
              className="flex items-center gap-1 bg-secondary/80 hover:bg-secondary text-white px-2 py-2 rounded-full shadow-lg transition-all duration-300"
            >
              <Search size={16} />
            </button>

            {/* Submit a Complaint Button */}
            <Link
              href="/complaints"
              className="flex items-center gap-2 bg-[#FF5722] hover:bg-[#E64A19] text-white px-3 py-2 rounded-full shadow-lg transition-all duration-300"
            >
              <AlertCircle size={18} />
              <span className="font-semibold text-xs">Submit a Complaint</span>
            </Link>
          </div>

          {/* Mobile Menu Button */}
          <button
            onClick={() => setIsOpen(!isOpen)}
            className="lg:hidden absolute right-0 text-white p-2 z-50"
            aria-label="Toggle menu"
          >
            {isOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />}
          </button>
            </div>
          </div>

          {/* Mobile Menu */}
          <AnimatePresence>
            {isOpen && (
              <motion.div
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: 'auto' }}
                exit={{ opacity: 0, height: 0 }}
                className="lg:hidden border-t border-white/10"
              >
            <div className="max-w-[900px] mx-auto px-4 py-4 space-y-2">
              {menuItems.map((item) => (
                <div key={item._id}>
                  <div className="flex items-center justify-between">
                    <Link
                      href={item.url || `/${item.slug}`}
                      className="block px-4 py-3 text-white hover:text-primary-light transition-colors duration-200 font-medium text-lg"
                      onClick={() => !item.children && setIsOpen(false)}
                    >
                      {item.title}
                    </Link>
                    {item.children && item.children.length > 0 && (
                      <button
                        onClick={() => toggleSubmenu(item._id)}
                        className="px-4 py-3 text-white"
                      >
                        <ChevronDown
                          className={`w-4 h-4 transition-transform duration-200 ${
                            activeSubmenu === item._id ? 'rotate-180' : ''
                          }`}
                        />
                      </button>
                    )}
                  </div>
                  <AnimatePresence>
                    {item.children && item.children.length > 0 && activeSubmenu === item._id && (
                      <motion.div
                        initial={{ opacity: 0, height: 0 }}
                        animate={{ opacity: 1, height: 'auto' }}
                        exit={{ opacity: 0, height: 0 }}
                        className="pl-8 space-y-1 glass-submenu rounded-lg my-2 mx-4 p-2"
                      >
                        {item.children.map((child, childIndex) => (
                          <motion.div
                            key={child._id}
                            initial={{ opacity: 0, x: -20 }}
                            animate={{ opacity: 1, x: 0 }}
                            exit={{ opacity: 0, x: -20 }}
                            transition={{ 
                              duration: 0.3, 
                              delay: childIndex * 0.05,
                              ease: 'easeOut'
                            }}
                          >
                            <Link
                              href={child.url || `/${child.slug}`}
                              className="block px-4 py-2 text-white/80 hover:text-primary-light transition-colors duration-200"
                              onClick={() => setIsOpen(false)}
                            >
                              {child.title}
                            </Link>
                          </motion.div>
                        ))}
                      </motion.div>
                    )}
                  </AnimatePresence>
                </div>
              ))}
            </div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </div>
      <SearchDialog isOpen={isSearchOpen} onClose={() => setIsSearchOpen(false)} />
    </nav>
  )
}
