'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { Search, Plus, Edit, Trash2, ChevronDown, ChevronRight } from 'lucide-react'
import { isAuthenticated } from '@/lib/auth'
import { apiGet, apiDelete } from '@/lib/apiClient'
import LoadingSpinner from '@/components/LoadingSpinner'

interface MenuItem {
  _id: string
  title: string
  slug: string
  url?: string
  order: number
  isActive: boolean
  children?: MenuItem[]
  parentId?: string
}

export default function MenuPage() {
  const router = useRouter()
  const [menuItems, setMenuItems] = useState<MenuItem[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [expandedItems, setExpandedItems] = useState<Set<string>>(new Set())

  useEffect(() => {
    if (!isAuthenticated()) {
      router.push('/admin')
      return
    }
    fetchMenu()
  }, [router])

  const fetchMenu = async () => {
    try {
      // Use /all endpoint to get all menu items including inactive ones
      const result = await apiGet<MenuItem[]>('/menu/all')
      if (result.success && result.data && Array.isArray(result.data)) {
        setMenuItems(result.data)
      } else {
        console.error('Unexpected menu response format:', result)
        setMenuItems([])
      }
    } catch (error: any) {
      console.error('Error fetching menu:', error)
      if (error.message?.includes('Authentication required')) {
        router.push('/admin')
      }
      setMenuItems([])
    } finally {
      setLoading(false)
    }
  }

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this menu item?')) return

    try {
      const result = await apiDelete(`/menu/${id}`)
      if (result.success) {
        fetchMenu()
      } else {
        alert(result.message || result.error || 'Failed to delete menu item')
      }
    } catch (error: any) {
      console.error('Error deleting menu item:', error)
      alert(error.message || 'Failed to delete menu item')
    }
  }

  const toggleExpand = (id: string) => {
    const newExpanded = new Set(expandedItems)
    if (newExpanded.has(id)) {
      newExpanded.delete(id)
    } else {
      newExpanded.add(id)
    }
    setExpandedItems(newExpanded)
  }

  const renderMenuItem = (item: MenuItem, level: number = 0): JSX.Element => {
    const isExpanded = expandedItems.has(item._id)
    const hasChildren = item.children && item.children.length > 0
    const matchesSearch = item.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
      item.slug.toLowerCase().includes(searchTerm.toLowerCase())

    if (searchTerm && !matchesSearch && (!hasChildren || !item.children?.some(child => 
      child.title.toLowerCase().includes(searchTerm.toLowerCase())
    ))) {
      return <></>
    }

    return (
      <div key={item._id} className={`${level > 0 ? 'ml-8 border-l-2 border-white/10 pl-4' : ''}`}>
        <div className="flex items-center gap-3 p-3 hover:bg-white/5 rounded-lg transition-colors">
          {/* Expand/Collapse */}
          {hasChildren && (
            <button
              onClick={() => toggleExpand(item._id)}
              className="p-1 text-white/50 hover:text-white"
            >
              {isExpanded ? (
                <ChevronDown className="w-4 h-4" />
              ) : (
                <ChevronRight className="w-4 h-4" />
              )}
            </button>
          )}
          {!hasChildren && <div className="w-6" />}

          {/* Order Badge */}
          <div className="w-8 h-8 flex items-center justify-center bg-primary/20 text-primary rounded-lg font-semibold text-xs">
            {item.order}
          </div>

          {/* Content */}
          <div className="flex-1">
            <div className="flex items-center gap-3">
              <p className="text-white font-medium">{item.title}</p>
              <code className="text-primary text-xs">/{item.slug}</code>
              {item.url && (
                <span className="text-white/50 text-xs">→ {item.url}</span>
              )}
              <span className={`px-2 py-1 text-xs font-medium rounded ${
                item.isActive 
                  ? 'bg-green-500/20 text-green-400' 
                  : 'bg-gray-500/20 text-gray-400'
              }`}>
                {item.isActive ? 'Active' : 'Inactive'}
              </span>
            </div>
          </div>

          {/* Actions */}
          <div className="flex items-center gap-2">
            <button
              onClick={() => router.push(`/admin/menu/${item._id}`)}
              className="p-2 text-blue-400 hover:bg-blue-500/20 rounded-lg transition-all"
              title="Edit"
            >
              <Edit className="w-4 h-4" />
            </button>
            <button
              onClick={() => handleDelete(item._id)}
              className="p-2 text-red-400 hover:bg-red-500/20 rounded-lg transition-all"
              title="Delete"
            >
              <Trash2 className="w-4 h-4" />
            </button>
          </div>
        </div>

        {/* Children */}
        {hasChildren && isExpanded && (
          <div className="mt-2">
            {item.children!.map(child => renderMenuItem(child, level + 1))}
          </div>
        )}
      </div>
    )
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <LoadingSpinner />
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-white mb-2">Menu Management</h1>
          <p className="text-white/70">Manage website navigation menu</p>
        </div>
        <button
          onClick={() => router.push('/admin/menu/new')}
          className="flex items-center gap-2 px-4 py-2 bg-primary hover:bg-primary-dark text-white rounded-lg transition-all"
        >
          <Plus className="w-5 h-5" />
          New Menu Item
        </button>
      </div>

      {/* Search */}
      <div className="bg-white/10 backdrop-blur-xl rounded-xl p-6 border border-white/20">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-white/50" />
          <input
            type="text"
            placeholder="Search menu items..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/40 focus:outline-none focus:ring-2 focus:ring-primary"
          />
        </div>
      </div>

      {/* Menu Items */}
      <div className="bg-white/10 backdrop-blur-xl rounded-xl border border-white/20 p-6">
        {menuItems.length > 0 ? (
          <div className="space-y-2">
            {menuItems.map(item => renderMenuItem(item))}
          </div>
        ) : (
          <div className="p-12 text-center">
            <p className="text-white/50">No menu items found</p>
          </div>
        )}
      </div>
    </div>
  )
}
