"use client"

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { useRouter, usePathname } from 'next/navigation'
import { cn } from '@/lib/utils'
import { Button } from '@/components/ui/button'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { Toaster } from '@/components/ui/toaster'
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarInset,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarProvider,
  SidebarTrigger,
} from '@/components/ui/sidebar'
import {
  BarChart3,
  FileText,
  Users,
  Settings,
  LogOut,
  Shield,
  Building,
  ChevronUp,
  User,
  Bell,
  HelpCircle,
  FileCheck,
  Clock,
  AlertTriangle,
  CheckCircle,
  Menu,
  X,
  Code,
  Mail,
  Phone,
  Layout,
  Image,
  MessageCircle,
  MapPin
} from 'lucide-react'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { useAdminAuth } from '@/hooks/useAdminAuth'

interface SystemSettings {
  siteName: string
  siteDescription: string
}

interface AdminSidebarProps {
  user?: any
  children?: React.ReactNode
}

const navigation = [
  {
    title: 'Utama',
    items: [
      {
        title: 'Dashboard',
        icon: BarChart3,
        href: '/admin/dashboard',
        badge: null,
      },
      {
        title: 'Pengajuan Masuk',
        icon: FileText,
        href: '/admin/requests',
        badge: 'new',
      },
    ],
  },
  {
    title: 'Manajemen',
    items: [
      {
        title: 'Kelola Layanan',
        icon: FileCheck,
        href: '/admin/services',
        badge: null,
      },
      {
        title: 'Kelola Template',
        icon: Code,
        href: '/admin/templates',
        badge: null,
      },
      {
        title: 'Slider/Banner',
        icon: Image,
        href: '/admin/sliders',
        badge: null,
      },
      {
        title: 'Landing Pages',
        icon: Layout,
        href: '/admin/landing-pages',
        badge: null,
      },
      {
        title: 'Manajemen Polsek & Polres',
        icon: Building,
        href: '/admin/police-management',
        badge: null,
      },
      {
        title: 'Social Media',
        icon: MessageCircle,
        href: '/admin/social-media',
        badge: null,
      },
      {
        title: 'Kelola Pengguna',
        icon: Users,
        href: '/admin/users',
        badge: null,
        role: 'SUPERADMIN',
      },
      {
        title: 'Permission',
        icon: Shield,
        href: '/admin/permissions',
        badge: null,
        role: 'SUPERADMIN',
      },
      {
        title: 'Kontak & Pesan',
        icon: Mail,
        href: '/admin/contacts',
        badge: null,
        role: 'ADMIN',
      },
    ],
  },
  {
    title: 'Lainnya',
    items: [
      {
        title: 'Pengaturan',
        icon: Settings,
        href: '/admin/settings',
        badge: null,
      },
      {
        title: 'Bantuan',
        icon: HelpCircle,
        href: '/admin/help',
        badge: null,
      },
    ],
  },
]

export function AdminSidebar({ user, children }: AdminSidebarProps) {
  const router = useRouter()
  const pathname = usePathname()
  const { logout, getAuthHeaders } = useAdminAuth()
  const [mounted, setMounted] = useState(false)
  const [settings, setSettings] = useState<SystemSettings>({
    siteName: 'Polres Wonosobo',
    siteDescription: 'Sistem Layanan Digital'
  })

  useEffect(() => {
    setMounted(true)
    fetchSettings()
  }, [])

  const fetchSettings = async () => {
    try {
      const response = await fetch('/api/admin/settings', {
        headers: getAuthHeaders()
      })

      if (response.ok) {
        const data = await response.json()
        if (data.settings) {
          setSettings({
            siteName: data.settings.siteName || 'Polres Wonosobo',
            siteDescription: data.settings.siteDescription || 'Sistem Layanan Digital'
          })
        }
      }
    } catch (error) {
      console.error('Error fetching settings:', error)
    }
  }

  const handleLogout = () => {
    logout()
  }

  if (!mounted) {
    return null
  }

  return (
    <SidebarProvider>
      <Sidebar className="border-r border-gray-200 bg-white">
        <SidebarHeader className="bg-gradient-to-r from-amber-600 to-amber-700 text-white">
          <div className="px-4 py-6">
            <div className="flex items-center gap-3">
              <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-white/20 backdrop-blur-sm">
                <Building className="h-6 w-6 text-white" />
              </div>
              <div>
                <h1 className="text-lg font-semibold text-white">{settings.siteName}</h1>
                <p className="text-xs text-amber-100">{settings.siteDescription}</p>
              </div>
            </div>
          </div>
        </SidebarHeader>

        <SidebarContent className="bg-gray-50">
          {navigation.map((section) => (
            <SidebarGroup key={section.title}>
              <SidebarGroupLabel className="px-4 text-xs font-semibold text-gray-500 uppercase tracking-wider">
                {section.title}
              </SidebarGroupLabel>
              <SidebarGroupContent>
                <SidebarMenu>
                  {section.items
                    .filter(item => !item.role || user?.role === item.role)
                    .map((item) => (
                    <SidebarMenuItem key={item.href}>
                      <SidebarMenuButton
                        asChild
                        isActive={pathname === item.href}
                        className={cn(
                          "hover:bg-amber-50 hover:text-amber-700 focus:bg-amber-50 focus:text-amber-700",
                          pathname === item.href && "bg-amber-50 text-amber-700 border-l-4 border-amber-600"
                        )}
                      >
                        <Link href={item.href}>
                          <item.icon className="h-4 w-4" />
                          <span className="font-medium">{item.title}</span>
                          {item.badge && (
                            <Badge variant="destructive" className="ml-auto h-5 px-1.5 text-xs">
                              {item.badge}
                            </Badge>
                          )}
                        </Link>
                      </SidebarMenuButton>
                    </SidebarMenuItem>
                  ))}
                </SidebarMenu>
              </SidebarGroupContent>
            </SidebarGroup>
          ))}
        </SidebarContent>

        <SidebarFooter className="border-t border-gray-200 bg-white p-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Avatar className="h-8 w-8">
                <AvatarImage src={user?.avatar} alt={user?.name} />
                <AvatarFallback className="bg-amber-100 text-amber-600 text-sm font-medium">
                  {user?.name?.charAt(0) || 'A'}
                </AvatarFallback>
              </Avatar>
              <div className="flex flex-col">
                <span className="text-sm font-medium text-gray-900">{user?.name}</span>
                <span className="text-xs text-gray-500">{user?.role}</span>
              </div>
            </div>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="sm" className="h-8 w-8 p-0">
                  <ChevronUp className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-48">
                <DropdownMenuItem>
                  <User className="mr-2 h-4 w-4" />
                  Profil Saya
                </DropdownMenuItem>
                <DropdownMenuItem>
                  <Settings className="mr-2 h-4 w-4" />
                  Pengaturan
                </DropdownMenuItem>
                <DropdownMenuItem>
                  <Bell className="mr-2 h-4 w-4" />
                  Notifikasi
                </DropdownMenuItem>
                <Separator />
                <DropdownMenuItem onClick={handleLogout}>
                  <LogOut className="mr-2 h-4 w-4" />
                  Keluar
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </SidebarFooter>
      </Sidebar>

      <SidebarInset className="bg-gray-50">
        <header className="flex h-16 shrink-0 items-center gap-2 border-b border-gray-200 bg-white px-4">
          <SidebarTrigger className="-ml-1 hover:bg-gray-100" />
          <Separator orientation="vertical" className="mr-2 h-4" />
          <div className="flex flex-1 items-center justify-between">
            <div>
              <h2 className="text-lg font-semibold text-gray-900">
                {navigation
                  .flatMap(section => section.items)
                  .find(item => item.href === pathname)?.title || 'Dashboard'}
              </h2>
            </div>
            <div className="flex items-center gap-2">
              <Button variant="ghost" size="sm" className="relative">
                <Bell className="h-4 w-4" />
                <span className="absolute -top-1 -right-1 h-3 w-3 rounded-full bg-red-500 text-[10px] text-white flex items-center justify-center">
                  3
                </span>
              </Button>
              <Button variant="ghost" size="sm">
                <HelpCircle className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </header>
        <div className="flex flex-1 flex-col gap-6 p-6 pt-0">
          <div className="max-w-7xl mx-auto w-full space-y-6">
            {children}
          </div>
        </div>
      </SidebarInset>
      <Toaster />
    </SidebarProvider>
  )
}