"use client"

import type React from "react"
import { useEffect } from "react"
import { useRouter, usePathname } from "next/navigation"
import Link from "next/link"
import {
  LayoutDashboard,
  Music,
  Disc3,
  BarChart3,
  Users,
  Settings,
  Upload,
  DollarSign,
  Menu,
  X,
  LogOut,
  Bell,
  Music2,
  User,
  Megaphone,
} from "lucide-react"
import { useState } from "react"
import { useAuth } from "@/components/auth-provider"
import useSWR from "swr"
import { NotificationDot } from "@/components/notification-badge"

const fetcher = (url: string) => fetch(url).then((res) => res.json())

const artistNavItems = [
  { href: "/artist", icon: LayoutDashboard, label: "Tableau de bord" },
  { href: "/artist/tracks", icon: Music, label: "Mes titres" },
  { href: "/artist/albums", icon: Disc3, label: "Mes albums" },
  { href: "/artist/upload", icon: Upload, label: "Uploader" },
  { href: "/artist/analytics", icon: BarChart3, label: "Statistiques" },
  { href: "/artist/audience", icon: Users, label: "Audience" },
  { href: "/artist/earnings", icon: DollarSign, label: "Revenus" },
  { href: "/artist/promotions", icon: Megaphone, label: "Promotions" },
  { href: "/artist/profile", icon: User, label: "Profil public" },
  { href: "/artist/settings", icon: Settings, label: "Parametres" },
]

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

  const { data: artistData } = useSWR(user?.artistId ? `/api/artists/${user.artistId}` : null, fetcher, {
    revalidateOnFocus: false,
    dedupingInterval: 60000, // Cache for 1 minute to prevent duplicate requests
    errorRetryCount: 2,
  })

  // Redirect if not logged in or not an artist
  useEffect(() => {
    if (!isLoading && (!isAuthenticated || user?.role !== "artist")) {
      router.push("/")
    }
  }, [isAuthenticated, isLoading, user, router])

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

  if (!isAuthenticated || user?.role !== "artist") {
    return null
  }

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

  const displayName = artistData?.name || user.artistProfile?.stageName || user.name
  const displayAvatar = artistData?.avatar_url || user.avatar || "/placeholder.svg"
  const isVerified = artistData?.is_verified || user.artistProfile?.verified

  return (
    <div className="min-h-screen bg-zinc-950 flex">
      {/* Mobile sidebar backdrop */}
      {sidebarOpen && (
        <div className="fixed inset-0 bg-black/50 z-40 lg:hidden" onClick={() => setSidebarOpen(false)} />
      )}

      {/* Sidebar */}
      <aside
        className={`fixed lg:static inset-y-0 left-0 z-50 w-64 bg-zinc-900 border-r border-zinc-800 transform transition-transform lg:transform-none ${
          sidebarOpen ? "translate-x-0" : "-translate-x-full lg:translate-x-0"
        }`}
      >
        <div className="flex flex-col h-full">
          {/* Logo */}
          <div className="flex items-center justify-between p-4 border-b border-zinc-800">
            <Link href="/artist" className="flex items-center gap-2">
              <div className="w-10 h-10 bg-gradient-to-br from-purple-500 to-pink-500 rounded-xl flex items-center justify-center">
                <Music2 className="w-6 h-6 text-white" />
              </div>
              <div>
                <span className="text-white font-bold">AfricanMusic</span>
                <span className="text-xs text-purple-400 block">Pour Artistes</span>
              </div>
            </Link>
            <button onClick={() => setSidebarOpen(false)} className="lg:hidden text-zinc-400 hover:text-white">
              <X className="w-5 h-5" />
            </button>
          </div>

          {/* Artist Profile - Now uses fresh data from API */}
          <div className="p-4 border-b border-zinc-800">
            <div className="flex items-center gap-3">
              <img
                src={displayAvatar || "/placeholder.svg"}
                alt={displayName}
                className="w-12 h-12 rounded-full object-cover"
              />
              <div className="flex-1 min-w-0">
                <p className="text-white font-medium truncate">{displayName}</p>
                <p className="text-xs text-zinc-400">{isVerified ? "Artiste verifie" : "Artiste"}</p>
              </div>
            </div>
          </div>

          {/* Navigation */}
          <nav className="flex-1 p-4 space-y-1 overflow-y-auto">
            {artistNavItems.map((item) => {
              const isActive = pathname === item.href
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  onClick={() => setSidebarOpen(false)}
                  className={`flex items-center gap-3 px-3 py-2.5 rounded-lg transition-colors ${
                    isActive
                      ? "bg-purple-500/20 text-purple-400"
                      : "text-zinc-400 hover:text-white hover:bg-zinc-800/50"
                  }`}
                >
                  <item.icon className="w-5 h-5" />
                  <span>{item.label}</span>
                </Link>
              )
            })}
          </nav>

          {/* Back to App & Logout */}
          <div className="p-4 border-t border-zinc-800 space-y-2">
            <Link
              href="/home"
              className="flex items-center gap-3 px-3 py-2.5 rounded-lg text-zinc-400 hover:text-white hover:bg-zinc-800/50 transition-colors w-full"
            >
              <Music className="w-5 h-5" />
              <span>Retour a l'app</span>
            </Link>
            <button
              onClick={handleLogout}
              className="flex items-center gap-3 px-3 py-2.5 rounded-lg text-zinc-400 hover:text-red-400 hover:bg-red-500/10 transition-colors w-full"
            >
              <LogOut className="w-5 h-5" />
              <span>Deconnexion</span>
            </button>
          </div>
        </div>
      </aside>

      {/* Main Content */}
      <div className="flex-1 flex flex-col min-h-screen">
        {/* Header - Now uses fresh data from API */}
        <header className="bg-zinc-900/50 backdrop-blur-xl border-b border-zinc-800 px-4 lg:px-6 py-4 flex items-center justify-between sticky top-0 z-30">
          <button onClick={() => setSidebarOpen(true)} className="lg:hidden text-zinc-400 hover:text-white">
            <Menu className="w-6 h-6" />
          </button>

          <div className="flex items-center gap-4 ml-auto">
            <Link href="/notifications-inbox" className="relative text-zinc-400 hover:text-white">
              <Bell className="w-5 h-5" />
              <NotificationDot />
            </Link>
            <Link href="/artist/settings">
              <img
                src={displayAvatar || "/placeholder.svg"}
                alt={displayName}
                className="w-8 h-8 rounded-full object-cover"
              />
            </Link>
          </div>
        </header>

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