'use client'

import { useState, useEffect } from 'react'
import { createPortal } from 'react-dom'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { 
  Menu, 
  X, 
  LayoutDashboard, 
  ShoppingCart, 
  Package, 
  Users, 
  MapPin, 
  Building2, 
  FileText, 
  Hexagon, 
  Settings,
  Bell,
  LogOut,
  HelpCircle,
  MessageSquare,
  Mail,
  FileDown
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'

type MobileMenuProps = {
  role: string | undefined
  siteName: string
  siteLogo: string | null
  picWhatsapp?: string
  picEmail?: string
}

export function MobileMenu({ role, siteName, siteLogo, picWhatsapp, picEmail }: MobileMenuProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [mounted, setMounted] = useState(false)
  const pathname = usePathname()

  // Set mounted state
  useEffect(() => {
    setMounted(true)
    return () => setMounted(false)
  }, [])

  // Close menu when route changes
  useEffect(() => {
    setIsOpen(false)
  }, [pathname])

  // Prevent background scroll when open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden'
    } else {
      document.body.style.overflow = 'unset'
    }
    return () => {
      document.body.style.overflow = 'unset'
    }
  }, [isOpen])

  return (
    <>
      <Button 
        variant="ghost" 
        size="icon" 
        onClick={() => setIsOpen(true)}
        className="md:hidden text-foreground hover:bg-muted"
        id="mobile-menu-trigger"
      >
        <Menu className="h-6 w-6" />
      </Button>

      {isOpen && createPortal(
        <>
          <div 
            className="fixed inset-0 bg-background/80 backdrop-blur-sm z-50 transition-all duration-300 md:hidden"
            onClick={() => setIsOpen(false)}
          />
          <div className="fixed inset-y-0 left-0 w-80 bg-background border-r border-border shadow-xl z-50 flex flex-col md:hidden animate-in slide-in-from-left duration-300">
            {/* Header */}
            <div className="h-16 flex items-center justify-between px-6 border-b border-border shrink-0">
              <div className="flex items-center">
                {siteLogo ? (
                  <img src={siteLogo} alt="Logo" className="h-8 w-8 mr-2 object-contain" />
                ) : (
                  <Hexagon className="h-6 w-6 text-primary mr-2 fill-primary/20" />
                )}
                <span className="text-lg font-extrabold bg-gradient-to-r from-primary to-indigo-600 bg-clip-text text-transparent">
                  {siteName}
                </span>
              </div>
              <Button 
                variant="ghost" 
                size="icon" 
                onClick={() => setIsOpen(false)}
                className="text-muted-foreground hover:text-foreground"
              >
                <X className="h-6 w-6" />
              </Button>
            </div>

            {/* Navigation */}
            <div className="flex-1 overflow-y-auto py-6 px-4 space-y-6">
              <div>
                <div className="px-3 mb-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                  Overview
                </div>
                <nav className="space-y-1">
                  <Link 
                    href="/dashboard" 
                    className={cn(
                      "flex items-center px-3 py-2.5 text-sm font-medium rounded-lg transition-colors group",
                      pathname === '/dashboard' 
                        ? "bg-primary/10 text-primary" 
                        : "text-muted-foreground hover:bg-muted hover:text-foreground"
                    )}
                  >
                    <LayoutDashboard className="mr-3 h-5 w-5 shrink-0" />
                    Dashboard
                  </Link>
                </nav>
              </div>

              <div>
                <div className="px-3 mb-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                  Procurement
                </div>
                <nav className="space-y-1">
                  {role !== 'ADMIN_APPROVAL' && role !== 'MANAGER' && (
                    <Link 
                      href="/dashboard/products" 
                      className={cn(
                        "flex items-center px-3 py-2.5 text-sm font-medium rounded-lg transition-colors group",
                        pathname === '/dashboard/products' 
                          ? "bg-primary/10 text-primary" 
                          : "text-muted-foreground hover:bg-muted hover:text-foreground"
                      )}
                    >
                      <Package className="mr-3 h-5 w-5 shrink-0" />
                      Products Catalog
                    </Link>
                  )}
                  <Link 
                    href="/dashboard/orders" 
                    className={cn(
                      "flex items-center px-3 py-2.5 text-sm font-medium rounded-lg transition-colors group",
                      pathname.startsWith('/dashboard/orders') 
                        ? "bg-primary/10 text-primary" 
                        : "text-muted-foreground hover:bg-muted hover:text-foreground"
                    )}
                  >
                    <ShoppingCart className="mr-3 h-5 w-5 shrink-0" />
                    Purchase Orders
                  </Link>
                </nav>
              </div>

              {role === 'SUPER_ADMIN_INTI' && (
                <div>
                  <div className="px-3 mb-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                    System Master
                  </div>
                  <nav className="space-y-1">
                    <Link 
                      href="/dashboard/users" 
                      className={cn(
                        "flex items-center px-3 py-2.5 text-sm font-medium rounded-lg transition-colors group",
                        pathname.startsWith('/dashboard/users') 
                          ? "bg-primary/10 text-primary" 
                          : "text-muted-foreground hover:bg-muted hover:text-foreground"
                      )}
                    >
                      <Users className="mr-3 h-5 w-5 shrink-0" />
                      User Management
                    </Link>
                    <Link 
                      href="/dashboard/departments" 
                      className={cn(
                        "flex items-center px-3 py-2.5 text-sm font-medium rounded-lg transition-colors group",
                        pathname === '/dashboard/departments' 
                          ? "bg-primary/10 text-primary" 
                          : "text-muted-foreground hover:bg-muted hover:text-foreground"
                      )}
                    >
                      <Building2 className="mr-3 h-5 w-5 shrink-0" />
                      Departments
                    </Link>
                    <Link 
                      href="/dashboard/regions" 
                      className={cn(
                        "flex items-center px-3 py-2.5 text-sm font-medium rounded-lg transition-colors group",
                        pathname === '/dashboard/regions' 
                          ? "bg-primary/10 text-primary" 
                          : "text-muted-foreground hover:bg-muted hover:text-foreground"
                      )}
                    >
                      <MapPin className="mr-3 h-5 w-5 shrink-0" />
                      Regions
                    </Link>
                    <Link 
                      href="/dashboard/reports" 
                      className={cn(
                        "flex items-center px-3 py-2.5 text-sm font-medium rounded-lg transition-colors group",
                        pathname === '/dashboard/reports' 
                          ? "bg-primary/10 text-primary" 
                          : "text-muted-foreground hover:bg-muted hover:text-foreground"
                      )}
                    >
                      <FileText className="mr-3 h-5 w-5 shrink-0" />
                      Audit Logs
                    </Link>
                  </nav>
                </div>
              )}

              <div>
                <div className="px-3 mb-2 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                  Personal
                </div>
                <nav className="space-y-1">
                  <Link 
                    href="/dashboard/settings" 
                    className={cn(
                      "flex items-center px-3 py-2.5 text-sm font-medium rounded-lg transition-colors group",
                      pathname === '/dashboard/settings' 
                        ? "bg-primary/10 text-primary" 
                        : "text-muted-foreground hover:bg-muted hover:text-foreground"
                    )}
                  >
                    <Settings className="mr-3 h-5 w-5 shrink-0" />
                    Settings
                  </Link>
                </nav>
              </div>
            </div>

            {/* Footer */}
            <div className="p-4 border-t border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-900/50 shrink-0">
              <div className="rounded-xl bg-gradient-to-br from-indigo-50 to-indigo-100/50 dark:from-slate-800/40 dark:to-slate-900/20 p-4 border border-slate-200/60 dark:border-slate-800/60 shadow-sm">
                <div className="flex items-center gap-2 mb-3">
                  <div className="p-1.5 rounded-lg bg-indigo-500/10 text-indigo-600 dark:text-indigo-400">
                    <HelpCircle className="h-4 w-4" />
                  </div>
                  <div>
                    <h4 className="text-xs font-bold text-slate-850 dark:text-slate-200 leading-tight">Help Center</h4>
                    <p className="text-[10px] text-slate-400 dark:text-slate-500 font-semibold leading-tight">Butuh bantuan?</p>
                  </div>
                </div>
                
                <div className="flex flex-col gap-1.5">
                  {picWhatsapp && (
                    <a 
                      href={`https://wa.me/${picWhatsapp.replace(/[^0-9]/g, '')}`} 
                      target="_blank" 
                      rel="noopener noreferrer" 
                      className="flex items-center gap-2 px-2.5 py-1.5 rounded-lg bg-emerald-500/[0.04] dark:bg-emerald-500/[0.02] border border-emerald-500/10 hover:bg-emerald-500/[0.08] text-emerald-600 dark:text-emerald-400 font-bold text-[11px] transition-all duration-200"
                    >
                      <MessageSquare className="h-3.5 w-3.5" />
                      <span>WhatsApp PIC</span>
                    </a>
                  )}
                  {picEmail && (
                    <a 
                      href={`mailto:${picEmail}`} 
                      className="flex items-center gap-2 px-2.5 py-1.5 rounded-lg bg-indigo-500/[0.04] dark:bg-indigo-500/[0.02] border border-indigo-500/10 hover:bg-indigo-500/[0.08] text-indigo-650 dark:text-indigo-400 font-bold text-[11px] transition-all duration-200"
                    >
                      <Mail className="h-3.5 w-3.5" />
                      <span>Email PIC</span>
                    </a>
                  )}
                  <a 
                    href="/api/guideline" 
                    download 
                    className="flex items-center gap-2 px-2.5 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-[11px] transition-all duration-200 shadow-sm shadow-indigo-600/10 mt-1"
                  >
                    <FileDown className="h-3.5 w-3.5" />
                    <span>Unduh Panduan PDF</span>
                  </a>
                </div>
              </div>
            </div>
          </div>
        </>,
        document.body
      )}
    </>
  )
}
