"use client"

import Image from "next/image"
import Link from "next/link"
import { ChevronLeft, RefreshCw, Loader2 } from "lucide-react"
import { BottomNav } from "@/components/bottom-nav"
import { SectionHeader } from "@/components/section-header"
import useSWR from "swr"

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

function MixGrid({ mixes, isLoading }: { mixes: any[]; isLoading: boolean }) {
  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-8">
        <Loader2 className="h-6 w-6 animate-spin text-primary" />
      </div>
    )
  }

  if (mixes.length === 0) {
    return (
      <div className="text-center py-8 text-muted-foreground">
        <p>Aucun mix disponible</p>
      </div>
    )
  }

  return (
    <div className="grid grid-cols-2 gap-4">
      {mixes.map((mix) => (
        <Link key={mix.id} href={`/playlist/${mix.id}`}>
          <div className="group">
            <div className="relative aspect-square overflow-hidden rounded-xl">
              <Image
                src={mix.cover_url || mix.image || "/placeholder.svg?height=200&width=200&query=music playlist"}
                alt={mix.name || mix.title}
                fill
                className="object-cover transition-transform group-hover:scale-105"
              />
              <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent" />
              <div className="absolute bottom-3 left-3 right-3">
                <h3 className="font-bold text-white">{mix.name || mix.title}</h3>
                <p className="text-xs text-white/70">{mix.description || `${mix.total_tracks || 0} titres`}</p>
              </div>
            </div>
          </div>
        </Link>
      ))}
    </div>
  )
}

export default function MixesPage() {
  const {
    data: playlistsData,
    isLoading,
    mutate,
  } = useSWR("/api/playlists?limit=50", fetcher, {
    dedupingInterval: 60000,
  })

  const { data: genresData, isLoading: genresLoading } = useSWR("/api/genres", fetcher, {
    dedupingInterval: 60000,
  })

  const playlists = playlistsData?.data || []
  const genres = genresData?.data || []

  // Filter playlists by type based on name/description keywords
  const dailyMixes = playlists
    .filter(
      (p: any) => p.name?.toLowerCase().includes("mix") || p.name?.toLowerCase().includes("jour") || p.is_editorial,
    )
    .slice(0, 4)

  // Create genre-based mixes from genres
  const genreMixes = genres.slice(0, 4).map((genre: any) => ({
    id: `genre-${genre.id}`,
    name: `Mix ${genre.name}`,
    description: genre.description || `Les meilleurs titres ${genre.name}`,
    cover_url: genre.icon_url,
    total_tracks: genre.track_count || 0,
  }))

  // Mood-based playlists
  const moodKeywords = ["chill", "relax", "focus", "party", "workout", "sleep", "energy"]
  const moodMixes = playlists
    .filter((p: any) =>
      moodKeywords.some(
        (keyword) => p.name?.toLowerCase().includes(keyword) || p.description?.toLowerCase().includes(keyword),
      ),
    )
    .slice(0, 4)

  const handleRefresh = () => {
    mutate()
  }

  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">Vos Mix</h1>
          </div>
          <button onClick={handleRefresh} className="rounded-full p-2 text-muted-foreground hover:text-foreground">
            <RefreshCw className="h-5 w-5" />
          </button>
        </div>

        {/* Daily Mixes */}
        <section className="mb-8">
          <SectionHeader title="Mix du Jour" />
          <div className="mt-4">
            <MixGrid mixes={dailyMixes.length > 0 ? dailyMixes : playlists.slice(0, 4)} isLoading={isLoading} />
          </div>
        </section>

        {/* Genre Mixes */}
        <section className="mb-8">
          <SectionHeader title="Par Genre" />
          <div className="mt-4">
            {genresLoading ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="h-6 w-6 animate-spin text-primary" />
              </div>
            ) : (
              <div className="grid grid-cols-2 gap-4">
                {genres.slice(0, 4).map((genre: any) => (
                  <Link key={genre.id} href={`/genre/${genre.id}`}>
                    <div className="group">
                      <div className="relative aspect-square overflow-hidden rounded-xl">
                        <Image
                          src={genre.icon_url || `/placeholder.svg?height=200&width=200&query=${genre.name} music`}
                          alt={genre.name}
                          fill
                          className="object-cover transition-transform group-hover:scale-105"
                        />
                        <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent" />
                        <div className="absolute bottom-3 left-3 right-3">
                          <h3 className="font-bold text-white">Mix {genre.name}</h3>
                          <p className="text-xs text-white/70">{genre.track_count || 0} titres</p>
                        </div>
                      </div>
                    </div>
                  </Link>
                ))}
              </div>
            )}
          </div>
        </section>

        {/* Mood Mixes */}
        <section className="mb-8">
          <SectionHeader title="Par Humeur" />
          <div className="mt-4">
            <MixGrid mixes={moodMixes.length > 0 ? moodMixes : playlists.slice(4, 8)} isLoading={isLoading} />
          </div>
        </section>
      </div>

      <BottomNav />
    </div>
  )
}
