"use client"

import { useState, useEffect } from "react"
import Image from "next/image"
import Link from "next/link"
import { ChevronDown, Share2, Heart } from "lucide-react"
import { usePlayer } from "@/components/player-provider"

interface LyricLine {
  time: number
  text: string
}

export default function LyricsPage() {
  const { currentTrack, isPlaying, progress, toggleLike, isLiked } = usePlayer()
  const [activeLine, setActiveLine] = useState(0)
  const [lyrics, setLyrics] = useState<LyricLine[]>([])
  const [isLoading, setIsLoading] = useState(false)

  useEffect(() => {
    async function fetchLyrics() {
      if (!currentTrack?.id) return

      try {
        setIsLoading(true)
        const response = await fetch(`/api/tracks/${currentTrack.id}`)
        if (response.ok) {
          const data = await response.json()

          // Check if lyrics are synced (timestamped) or plain text
          if (data.lyrics_synced && Array.isArray(data.lyrics_synced)) {
            // Use synced lyrics with timestamps
            setLyrics(data.lyrics_synced)
          } else if (data.lyrics) {
            // Convert plain text lyrics to format without timestamps
            const lines = data.lyrics.split("\n").map((text: string, index: number) => ({
              time: index * 4, // Simple fallback: 4 seconds per line
              text: text.trim(),
            }))
            setLyrics(lines)
          } else {
            // No lyrics available
            setLyrics([])
          }
        }
      } catch (error) {
        console.error("Error fetching lyrics:", error)
        setLyrics([])
      } finally {
        setIsLoading(false)
      }
    }

    fetchLyrics()
  }, [currentTrack?.id])

  useEffect(() => {
    if (lyrics.length === 0) return

    // Find the current active line based on progress
    const currentLine = lyrics.reduce((acc, line, index) => {
      if (line.time <= progress) return index
      return acc
    }, 0)
    setActiveLine(currentLine)
  }, [progress, lyrics])

  if (!currentTrack) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background">
        <p className="text-muted-foreground">Aucune piste en lecture</p>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background">
      {/* Background blur */}
      <div className="fixed inset-0 -z-10">
        <Image
          src={currentTrack.image || "/placeholder.svg"}
          alt=""
          fill
          className="object-cover opacity-30 blur-3xl"
        />
        <div className="absolute inset-0 bg-gradient-to-b from-background/60 to-background" />
      </div>

      <div className="mx-auto max-w-md px-4 py-6">
        {/* Header */}
        <div className="mb-6 flex items-center justify-between">
          <Link href="/now-playing" className="text-foreground hover:text-primary">
            <ChevronDown className="h-6 w-6" />
          </Link>
          <div className="text-center">
            <p className="text-sm font-semibold text-foreground">{currentTrack.title}</p>
            <p className="text-xs text-muted-foreground">{currentTrack.artist}</p>
          </div>
          <div className="flex gap-2">
            <button
              onClick={() => toggleLike(currentTrack.id)}
              className={isLiked(currentTrack.id) ? "text-primary" : "text-muted-foreground hover:text-foreground"}
            >
              <Heart className={`h-5 w-5 ${isLiked(currentTrack.id) ? "fill-current" : ""}`} />
            </button>
            <button className="text-muted-foreground hover:text-foreground">
              <Share2 className="h-5 w-5" />
            </button>
          </div>
        </div>

        {/* Lyrics */}
        <div className="space-y-4 py-8">
          {isLoading ? (
            <p className="text-center text-muted-foreground">Chargement des paroles...</p>
          ) : lyrics.length === 0 ? (
            <p className="text-center text-muted-foreground">Aucune parole disponible pour ce titre</p>
          ) : (
            lyrics.map((line, index) => (
              <p
                key={index}
                className={`text-center text-lg transition-all duration-300 ${
                  index === activeLine
                    ? "text-2xl font-bold text-foreground scale-105"
                    : index < activeLine
                      ? "text-muted-foreground/50"
                      : "text-muted-foreground"
                }`}
              >
                {line.text || "\u00A0"}
              </p>
            ))
          )}
        </div>

        {/* Playing indicator */}
        <div className="fixed bottom-8 left-0 right-0 flex justify-center">
          <div className="flex items-center gap-2 rounded-full bg-secondary/80 px-4 py-2 backdrop-blur-sm">
            <div className={`flex gap-1 ${isPlaying ? "animate-pulse" : ""}`}>
              <span className="h-3 w-1 rounded-full bg-primary" />
              <span className="h-4 w-1 rounded-full bg-primary" />
              <span className="h-2 w-1 rounded-full bg-primary" />
            </div>
            <span className="text-sm text-foreground">{isPlaying ? "En lecture" : "En pause"}</span>
          </div>
        </div>
      </div>
    </div>
  )
}
