"use client"

import { useState, useEffect } from "react"
import { ChevronLeft, Grid2x2, List, Shuffle, Plus, Heart, Download, User, Clock, Loader2 } from "lucide-react"
import Link from "next/link"
import { BottomNav } from "@/components/bottom-nav"
import { PlaylistItem } from "@/components/playlist-item"
import { StorageBar } from "@/components/storage-bar"
import { SectionHeader } from "@/components/section-header"
import useSWR from "swr"
import { useAuth } from "@/components/auth-provider"
import { offlineStorage } from "@/lib/offline-storage"

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

export default function LibraryPage() {
  const [viewMode, setViewMode] = useState<"list" | "grid">("list")
  const { user } = useAuth()
  const [offlineDownloadsCount, setOfflineDownloadsCount] = useState(0)

  const { data: playlistsData, isLoading: playlistsLoading } = useSWR(user ? "/api/playlists" : null, fetcher)
  const { data: statsData, isLoading: statsLoading } = useSWR(
    user ? `/api/library/stats?userId=${user.id}` : null,
    fetcher,
    { dedupingInterval: 30000 },
  )

  useEffect(() => {
    async function loadOfflineDownloads() {
      if (!user?.id || !offlineStorage) return

      try {
        await offlineStorage.initForUser(user.id)
        const tracks = await offlineStorage.getAllTracks()
        setOfflineDownloadsCount(tracks.length)
      } catch (error) {
        console.error("[v0] Library - Failed to load offline downloads:", error)
        setOfflineDownloadsCount(0)
      }
    }

    loadOfflineDownloads()
    const interval = setInterval(loadOfflineDownloads, 10000)
    return () => clearInterval(interval)
  }, [user?.id])

  const playlists = playlistsData?.data || []

  const quickAccess = [
    { id: "liked", title: "Titres likés", icon: Heart, href: "/liked", count: statsData?.likedTracks ?? 0 },
    { id: "downloads", title: "Téléchargements", icon: Download, href: "/downloads", count: offlineDownloadsCount },
    { id: "artists", title: "Artistes", icon: User, href: "/artists", count: statsData?.followedArtists ?? 0 },
    {
      id: "recent",
      title: "Récemment joués",
      icon: Clock,
      href: "/library/recent",
      count: statsData?.recentlyPlayed ?? 0,
    },
  ]

  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-6 flex items-center justify-between">
          <div className="flex items-center gap-4">
            <Link href="/" className="text-foreground hover:text-primary">
              <ChevronLeft className="h-6 w-6" />
            </Link>
            <h1 className="text-xl font-bold text-foreground">Votre Bibliothèque</h1>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setViewMode("list")}
              className={`rounded-lg p-2 ${viewMode === "list" ? "bg-secondary text-foreground" : "text-muted-foreground"}`}
            >
              <List className="h-5 w-5" />
            </button>
            <button
              onClick={() => setViewMode("grid")}
              className={`rounded-lg p-2 ${viewMode === "grid" ? "bg-secondary text-foreground" : "text-muted-foreground"}`}
            >
              <Grid2x2 className="h-5 w-5" />
            </button>
            <button className="rounded-lg p-2 text-muted-foreground hover:text-foreground">
              <Shuffle className="h-5 w-5" />
            </button>
          </div>
        </div>

        <section className="mb-6">
          <div className="grid grid-cols-2 gap-2">
            {statsLoading ? (
              <div className="col-span-2 flex justify-center py-4">
                <Loader2 className="h-6 w-6 animate-spin text-primary" />
              </div>
            ) : (
              quickAccess.map((item) => (
                <Link key={item.id} href={item.href}>
                  <div className="flex items-center gap-3 rounded-lg bg-secondary/50 p-3 transition-colors hover:bg-secondary">
                    <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/20">
                      <item.icon className="h-5 w-5 text-primary" />
                    </div>
                    <div>
                      <h3 className="text-sm font-medium text-foreground">{item.title}</h3>
                      <p className="text-xs text-muted-foreground">{item.count} titres</p>
                    </div>
                  </div>
                </Link>
              ))
            )}
          </div>
        </section>

        {/* Playlists Section */}
        <section className="mb-8">
          <div className="mb-4 flex items-center justify-between">
            <SectionHeader title="Playlists" href="/library/playlists" />
            <Link href="/playlist/create" className="rounded-full bg-primary p-2 text-primary-foreground">
              <Plus className="h-4 w-4" />
            </Link>
          </div>
          {playlistsLoading ? (
            <div className="flex justify-center py-8">
              <Loader2 className="w-6 h-6 animate-spin text-primary" />
            </div>
          ) : playlists.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              <p>Aucune playlist</p>
              <Link href="/playlist/create" className="text-primary hover:underline mt-2 inline-block">
                Créer votre première playlist
              </Link>
            </div>
          ) : viewMode === "list" ? (
            <div className="mt-4 space-y-1">
              {playlists.map((playlist: any) => (
                <PlaylistItem
                  key={playlist.id}
                  id={playlist.id}
                  title={playlist.name || playlist.title}
                  subtitle={`${playlist.track_count || 0} titres`}
                  image={playlist.cover_url || "/music-playlist.png"}
                  icon="music"
                  href={`/playlist/${playlist.id}`}
                />
              ))}
            </div>
          ) : (
            <div className="mt-4 grid grid-cols-2 gap-3">
              {playlists.map((playlist: any) => (
                <Link key={playlist.id} href={`/playlist/${playlist.id}`}>
                  <div className="group">
                    <div className="aspect-square overflow-hidden rounded-lg bg-secondary">
                      <img
                        src={playlist.cover_url || "/music-playlist.png"}
                        alt={playlist.name}
                        className="h-full w-full object-cover transition-transform group-hover:scale-105"
                      />
                    </div>
                    <h3 className="mt-2 text-sm font-medium text-foreground truncate">{playlist.name}</h3>
                    <p className="text-xs text-muted-foreground">{playlist.track_count || 0} titres</p>
                  </div>
                </Link>
              ))}
            </div>
          )}
        </section>

        <section className="mb-8">
          <StorageBar used={statsData?.storageUsedGB ?? 0} total={statsData?.storageTotalGB ?? 64} />
        </section>
      </div>

      <BottomNav />
    </div>
  )
}
