"use client"
import { useRouter } from "next/navigation"
import { BottomNav } from "@/components/bottom-nav"
import { useTheme } from "next-themes"
import { useState, useEffect } from "react"
import {
  ChevronLeft,
  Settings,
  Bell,
  Moon,
  Sun,
  LogOut,
  Music,
  Heart,
  Download,
  Clock,
  Mic2,
  Shield,
  CreditCard,
  ChevronRight,
  User,
  ShoppingBag,
} from "lucide-react"
import Link from "next/link"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Switch } from "@/components/ui/switch"
import { useAuth } from "@/components/auth-provider"
import { Badge } from "@/components/ui/badge"
import { NotificationBadge } from "@/components/notification-badge"

export default function ProfilePage() {
  const router = useRouter()
  const { theme, setTheme } = useTheme() // Use next-themes for dark mode
  const { user, isAuthenticated, logout } = useAuth()

  const [stats, setStats] = useState([
    { label: "Titres likés", value: 0, icon: Heart, href: "/liked" },
    { label: "Téléchargements", value: 0, icon: Download, href: "/downloads" },
    { label: "Écoutés", value: 0, icon: Clock, href: "/library/recent" },
  ])

  useEffect(() => {
    const fetchStats = async () => {
      if (!isAuthenticated || !user?.id) return

      try {
        const response = await fetch(`/api/library/stats?userId=${user.id}`)
        if (response.ok) {
          const data = await response.json()
          setStats([
            { label: "Titres likés", value: data.likedTracks || 0, icon: Heart, href: "/liked" },
            { label: "Téléchargements", value: data.downloads || 0, icon: Download, href: "/downloads" },
            { label: "Écoutés", value: data.recentlyPlayed || 0, icon: Clock, href: "/library/recent" },
          ])
        }
      } catch (error) {
        console.error("Failed to fetch stats:", error)
      }
    }

    fetchStats()
  }, [isAuthenticated, user?.id])

  const getInitials = (name: string) => {
    return name
      .split(" ")
      .map((n) => n[0])
      .join("")
      .toUpperCase()
      .slice(0, 2)
  }

  const getPlanBadge = () => {
    if (!user?.subscription) return null
    switch (user.subscription.plan) {
      case "premium":
        return <Badge className="bg-purple-500/20 text-purple-400 border-0">Premium</Badge>
      case "family":
        return <Badge className="bg-blue-500/20 text-blue-400 border-0">Famille</Badge>
      case "student":
        return <Badge className="bg-cyan-500/20 text-cyan-400 border-0">Etudiant</Badge>
      default:
        return <Badge className="bg-zinc-500/20 text-zinc-400 border-0">Gratuit</Badge>
    }
  }

  return (
    <div className="min-h-screen bg-background pb-24">
      <div className="mx-auto max-w-md px-4 py-6">
        {/* Header */}
        <div className="mb-8 flex items-center gap-4">
          <Link href="/home" className="text-foreground hover:text-primary">
            <ChevronLeft className="h-6 w-6" />
          </Link>
          <h1 className="text-xl font-bold text-foreground">Compte</h1>
        </div>

        {/* Profile Info */}
        {isAuthenticated && user ? (
          <div className="mb-8 flex flex-col items-center">
            <Avatar className="mb-4 h-24 w-24">
              <AvatarImage src={user.avatar || "/placeholder.svg"} alt={user.name} />
              <AvatarFallback>{getInitials(user.name)}</AvatarFallback>
            </Avatar>
            <h2 className="text-xl font-semibold text-foreground">{user.name}</h2>
            <p className="text-muted-foreground">{user.email}</p>
            <div className="mt-2 flex items-center gap-2">
              {getPlanBadge()}
              {user.role === "artist" && <Badge className="bg-pink-500/20 text-pink-400 border-0">Artiste</Badge>}
              {user.role === "admin" && <Badge className="bg-red-500/20 text-red-400 border-0">Admin</Badge>}
            </div>
          </div>
        ) : (
          <div className="mb-8 flex flex-col items-center">
            <div className="mb-4 h-24 w-24 rounded-full bg-secondary flex items-center justify-center">
              <User className="h-12 w-12 text-muted-foreground" />
            </div>
            <h2 className="text-xl font-semibold text-foreground">Visiteur</h2>
            <p className="text-muted-foreground mb-4">Connectez-vous pour acceder a votre compte</p>
            <Link
              href="/"
              className="px-6 py-2 bg-primary text-primary-foreground rounded-full font-medium hover:bg-primary/90 transition-colors"
            >
              Se connecter
            </Link>
          </div>
        )}

        {/* Stats */}
        <div className="mb-8 grid grid-cols-3 gap-2">
          {stats.map((stat) => (
            <Link
              key={stat.label}
              href={stat.href}
              className="flex flex-col items-center gap-1 rounded-xl bg-secondary/50 p-4 transition-colors hover:bg-secondary"
            >
              <stat.icon className="h-5 w-5 text-primary" />
              <span className="text-xl font-bold text-foreground">{stat.value}</span>
              <span className="text-xs text-muted-foreground text-center">{stat.label}</span>
            </Link>
          ))}
        </div>

        {/* Role-specific links */}
        {isAuthenticated && user?.role === "artist" && (
          <div className="mb-4">
            <Link
              href="/artist"
              className="flex items-center gap-4 rounded-xl bg-gradient-to-r from-purple-500/20 to-pink-500/20 p-4 border border-purple-500/30 transition-colors hover:from-purple-500/30 hover:to-pink-500/30"
            >
              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-purple-500/20">
                <Mic2 className="h-5 w-5 text-purple-400" />
              </div>
              <div className="flex-1">
                <span className="font-medium text-foreground">Espace Artiste</span>
                <p className="text-xs text-muted-foreground">Gerez vos titres et statistiques</p>
              </div>
              <ChevronRight className="h-5 w-5 text-muted-foreground" />
            </Link>
          </div>
        )}

        {isAuthenticated && user?.role === "admin" && (
          <div className="mb-4">
            <Link
              href="/admin"
              className="flex items-center gap-4 rounded-xl bg-gradient-to-r from-red-500/20 to-orange-500/20 p-4 border border-red-500/30 transition-colors hover:from-red-500/30 hover:to-orange-500/30"
            >
              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-red-500/20">
                <Shield className="h-5 w-5 text-red-400" />
              </div>
              <div className="flex-1">
                <span className="font-medium text-foreground">Administration</span>
                <p className="text-xs text-muted-foreground">Acceder au panneau d'administration</p>
              </div>
              <ChevronRight className="h-5 w-5 text-muted-foreground" />
            </Link>
          </div>
        )}

        {/* Menu Items */}
        <div className="space-y-2">
          {isAuthenticated && (
            <Link
              href="/profile/edit"
              className="flex items-center gap-4 rounded-lg p-4 transition-colors hover:bg-secondary"
            >
              <User className="h-5 w-5 text-muted-foreground" />
              <span className="flex-1 text-foreground">Modifier le profil</span>
              <ChevronRight className="h-5 w-5 text-muted-foreground" />
            </Link>
          )}

          {isAuthenticated && user?.subscription?.plan === "free" && (
            <Link
              href="/premium"
              className="flex items-center gap-4 rounded-lg p-4 transition-colors hover:bg-secondary"
            >
              <CreditCard className="h-5 w-5 text-muted-foreground" />
              <span className="flex-1 text-foreground">Passer a Premium</span>
              <ChevronRight className="h-5 w-5 text-muted-foreground" />
            </Link>
          )}

          {isAuthenticated && (
            <Link
              href="/purchases"
              className="flex items-center gap-4 rounded-lg p-4 transition-colors hover:bg-secondary"
            >
              <ShoppingBag className="h-5 w-5 text-muted-foreground" />
              <span className="flex-1 text-foreground">Mes achats</span>
              <ChevronRight className="h-5 w-5 text-muted-foreground" />
            </Link>
          )}

          <Link
            href="/settings"
            className="flex items-center gap-4 rounded-lg p-4 transition-colors hover:bg-secondary"
          >
            <Settings className="h-5 w-5 text-muted-foreground" />
            <span className="flex-1 text-foreground">Paramètres</span>
            <ChevronRight className="h-5 w-5 text-muted-foreground" />
          </Link>

          <Link
            href="/notifications-inbox"
            className="flex items-center gap-4 rounded-lg p-4 transition-colors hover:bg-secondary"
          >
            <Bell className="h-5 w-5 text-muted-foreground" />
            <span className="flex-1 text-foreground">Notifications</span>
            <NotificationBadge />
          </Link>

          <div className="flex items-center gap-4 rounded-lg p-4">
            {theme === "dark" ? (
              <Moon className="h-5 w-5 text-muted-foreground" />
            ) : (
              <Sun className="h-5 w-5 text-muted-foreground" />
            )}
            <span className="flex-1 text-foreground">Mode sombre</span>
            <Switch checked={theme === "dark"} onCheckedChange={(checked) => setTheme(checked ? "dark" : "light")} />
          </div>

          <Link href="/library" className="flex items-center gap-4 rounded-lg p-4 transition-colors hover:bg-secondary">
            <Music className="h-5 w-5 text-muted-foreground" />
            <span className="flex-1 text-foreground">Ma bibliothèque</span>
            <ChevronRight className="h-5 w-5 text-muted-foreground" />
          </Link>

          {isAuthenticated ? (
            <button
              onClick={() => logout()}
              className="flex w-full items-center gap-4 rounded-lg p-4 text-destructive transition-colors hover:bg-secondary"
            >
              <LogOut className="h-5 w-5" />
              <span>Déconnexion</span>
            </button>
          ) : (
            <Link
              href="/signup"
              className="flex w-full items-center gap-4 rounded-lg p-4 text-primary transition-colors hover:bg-secondary"
            >
              <User className="h-5 w-5" />
              <span>Creer un compte</span>
            </Link>
          )}
        </div>
      </div>

      <BottomNav />
    </div>
  )
}
