"use client"

import type React from "react"
import { useEffect } from "react"
import Link from "next/link"
import { usePathname, useRouter } from "next/navigation"
import {
  LayoutDashboard,
  Users,
  Music,
  Disc3,
  Mic2,
  ListMusic,
  BarChart3,
  Shield,
  Settings,
  Bell,
  Search,
  Menu,
  ChevronDown,
  LogOut,
  FileText,
  DollarSign,
  ScrollText,
  CreditCard,
  Tag,
  FolderTree,
  Megaphone,
  HeadphonesIcon,
  Coins,
  Database,
  Key,
  BadgeCheck,
  Activity,
  HardDrive,
  AudioWaveform,
  Download,
  Video,
} from "lucide-react"
import { useState } from "react"
import { Suspense } from "react"
import { cn } from "@/lib/utils"
import Image from "next/image"
import { useAuth } from "@/components/auth-provider"
import { AdminProvider } from "@/components/admin-provider"

const sidebarItems = [
  { name: "Tableau de bord", href: "/admin", icon: LayoutDashboard },
  { name: "Utilisateurs", href: "/admin/users", icon: Users },
  { name: "Abonnements", href: "/admin/subscriptions", icon: CreditCard },
  { name: "Titres", href: "/admin/tracks", icon: Music },
  { name: "Vidéos", href: "/admin/videos", icon: Video },
  { name: "Albums", href: "/admin/albums", icon: Disc3 },
  { name: "Artistes", href: "/admin/artists", icon: Mic2 },
  { name: "Verification", href: "/admin/verification", icon: BadgeCheck },
  { name: "Playlists", href: "/admin/playlists", icon: ListMusic },
  { name: "Genres", href: "/admin/genres", icon: Tag },
  { name: "Categories", href: "/admin/categories", icon: FolderTree },
  { name: "Promotions", href: "/admin/promotions", icon: Megaphone },
  { name: "Notifications", href: "/admin/notifications", icon: Bell },
  { name: "Support", href: "/admin/support", icon: HeadphonesIcon },
  { name: "Royalties", href: "/admin/royalties", icon: Coins },
  { name: "Analytiques", href: "/admin/analytics", icon: BarChart3 },
  { name: "Rapports", href: "/admin/reports", icon: FileText },
  { name: "Revenus", href: "/admin/revenue", icon: DollarSign },
  { name: "Moderation", href: "/admin/moderation", icon: Shield },
  { name: "Logs", href: "/admin/logs", icon: ScrollText },
  { name: "Sauvegardes", href: "/admin/backups", icon: Database },
  { name: "API Sonneries", href: "/admin/ringtone-api", icon: Key },
  { name: "Téléchargements RBT", href: "/admin/ringtone-api/downloads", icon: Download },
  { name: "Monitoring API", href: "/admin/api-monitoring", icon: Activity },
  { name: "API", href: "/admin/api", icon: Key },
  { name: "Stockage", href: "/admin/storage", icon: HardDrive },
  { name: "Convertisseur Audio", href: "/admin/audio-converter", icon: AudioWaveform },
  { name: "Paramètres", href: "/admin/settings", icon: Settings },
]

export default function AdminLayout({ children }: { children: React.ReactNode }) {
  const pathname = usePathname()
  const router = useRouter()
  const { user, isAuthenticated, isLoading, logout } = useAuth()
  const [sidebarOpen, setSidebarOpen] = useState(false)
  const [userMenuOpen, setUserMenuOpen] = useState(false)

  useEffect(() => {
    console.log("[v0] Admin Layout - Auth State:", {
      isLoading,
      isAuthenticated,
      userRole: user?.role,
      userId: user?.id,
      userEmail: user?.email,
    })

    if (!isLoading) {
      if (!isAuthenticated) {
        console.log("[v0] Not authenticated, redirecting to login")
        router.push("/?redirect=/admin")
      } else if (user?.role !== "admin") {
        console.log("[v0] User is not admin, role is:", user?.role)
        router.push("/home")
      } else {
        console.log("[v0] Admin access granted")
      }
    }
  }, [isAuthenticated, isLoading, user, router])

  const handleLogout = () => {
    logout()
    router.push("/")
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-primary"></div>
      </div>
    )
  }

  if (!isAuthenticated) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-foreground mb-4">Non autorisé</h1>
          <p className="text-muted-foreground mb-6">Vous devez être connecté pour accéder à cette page.</p>
          <Link href="/?redirect=/admin" className="text-primary hover:text-primary/80">
            Se connecter
          </Link>
        </div>
      </div>
    )
  }

  if (user?.role !== "admin") {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-foreground mb-4">Accès refusé</h1>
          <p className="text-muted-foreground mb-6">
            Vous n'avez pas les permissions nécessaires pour accéder à cette page.
          </p>
          <p className="text-sm text-muted-foreground/70 mb-6">Votre rôle actuel : {user?.role}</p>
          <Link href="/home" className="text-primary hover:text-primary/80">
            Retour à l'accueil
          </Link>
        </div>
      </div>
    )
  }

  return (
    <AdminProvider>
      <Suspense fallback={<div>Loading...</div>}>
        <div className="flex min-h-screen bg-background">
          {/* Sidebar */}
          <aside
            className={cn(
              "fixed inset-y-0 left-0 z-50 flex w-64 flex-col border-r border-border bg-card transition-transform lg:static lg:translate-x-0",
              sidebarOpen ? "translate-x-0" : "-translate-x-full",
            )}
          >
            {/* Logo */}
            <div className="flex h-16 items-center gap-2 border-b border-border px-6">
              <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary">
                <Music className="h-4 w-4 text-primary-foreground" />
              </div>
              <span className="text-lg font-semibold text-foreground">Musique Admin</span>
            </div>

            {/* Nav Items */}
            <nav className="flex-1 overflow-y-auto p-4">
              <ul className="space-y-1">
                {sidebarItems.map((item) => {
                  const isActive = pathname === item.href || (item.href !== "/admin" && pathname.startsWith(item.href))
                  return (
                    <li key={item.href}>
                      <Link
                        href={item.href}
                        onClick={() => setSidebarOpen(false)}
                        className={cn(
                          "flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-colors",
                          isActive
                            ? "bg-primary/20 text-foreground"
                            : "text-muted-foreground hover:bg-accent hover:text-accent-foreground",
                        )}
                      >
                        <item.icon className={cn("h-4 w-4", isActive && "text-primary")} />
                        {item.name}
                      </Link>
                    </li>
                  )
                })}
              </ul>
            </nav>

            {/* Bottom link to app */}
            <div className="border-t border-border p-4">
              <Link
                href="/home"
                className="flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-accent-foreground"
              >
                <LogOut className="h-5 w-5" />
                Retour à l'app
              </Link>
            </div>
          </aside>

          {/* Main Content */}
          <div className="flex flex-1 flex-col">
            {/* Top Bar */}
            <header className="sticky top-0 z-40 flex h-16 items-center gap-4 border-b border-border bg-background/80 px-4 backdrop-blur-xl lg:px-6">
              <button
                onClick={() => setSidebarOpen(!sidebarOpen)}
                className="text-muted-foreground hover:text-foreground lg:hidden"
              >
                <Menu className="h-6 w-6" />
              </button>

              {/* Search */}
              <div className="relative flex-1 max-w-md">
                <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <input
                  type="text"
                  placeholder="Rechercher..."
                  className="h-10 w-full rounded-lg border border-border bg-input pl-10 pr-4 text-sm text-foreground placeholder-muted-foreground focus:border-primary focus:outline-none focus:ring-1 focus:ring-ring"
                />
              </div>

              <div className="flex items-center gap-4">
                {/* Notifications */}
                <button className="relative text-muted-foreground hover:text-foreground">
                  <Bell className="h-5 w-5" />
                  <span className="absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full bg-destructive text-[10px] text-destructive-foreground">
                    3
                  </span>
                </button>

                {/* User Menu */}
                <div className="relative">
                  <button
                    onClick={() => setUserMenuOpen(!userMenuOpen)}
                    className="flex items-center gap-2 rounded-lg p-1.5 hover:bg-accent"
                  >
                    <div className="h-8 w-8 overflow-hidden rounded-full">
                      <Image
                        src={user?.avatar || "/woman-profile-avatar.png"}
                        alt="Admin"
                        width={32}
                        height={32}
                        className="h-full w-full object-cover"
                      />
                    </div>
                    <span className="hidden text-sm font-medium text-foreground md:block">{user?.name || "Admin"}</span>
                    <ChevronDown className="h-4 w-4 text-muted-foreground" />
                  </button>

                  {userMenuOpen && (
                    <div className="absolute right-0 top-full mt-2 w-48 rounded-lg border border-border bg-popover py-1 shadow-xl">
                      <Link
                        href="/admin/settings"
                        className="block px-4 py-2 text-sm text-popover-foreground hover:bg-accent hover:text-accent-foreground"
                      >
                        Paramètres
                      </Link>
                      <button
                        onClick={handleLogout}
                        className="block w-full text-left px-4 py-2 text-sm text-popover-foreground hover:bg-accent hover:text-accent-foreground"
                      >
                        Déconnexion
                      </button>
                    </div>
                  )}
                </div>
              </div>
            </header>

            {/* Page Content */}
            <main className="flex-1 overflow-auto p-4 lg:p-6">{children}</main>
          </div>

          {/* Mobile overlay */}
          {sidebarOpen && (
            <div
              className="fixed inset-0 z-40 bg-black/60 backdrop-blur-sm lg:hidden"
              onClick={() => setSidebarOpen(false)}
            />
          )}
        </div>
      </Suspense>
    </AdminProvider>
  )
}
