"use client"

import { Suspense } from "react"
import { useSearchParams, useRouter } from "next/navigation"
import Image from "next/image"
import Link from "next/link"
import { ChevronLeft, Play, Loader2 } from "lucide-react"
import { BottomNav } from "@/components/bottom-nav"
import { Button } from "@/components/ui/button"
import { usePlayer } from "@/components/player-provider"
import useSWR from "swr"

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

function SearchResultsContent() {
  const searchParams = useSearchParams()
  const router = useRouter()
  const query = searchParams.get("q") || ""

  const { playTrack, currentTrack, isPlaying, togglePlay, playAlbum } = usePlayer()

  // Fetch search results from API
  const { data: searchData, isLoading } = useSWR(query ? `/api/search?q=${encodeURIComponent(query)}` : null, fetcher)

  const artists = searchData?.artists || []
  const tracks = searchData?.tracks || []
  const albums = searchData?.albums || []
  const playlists = searchData?.playlists || []

  const formatDuration = (ms: number) => {
    const minutes = Math.floor(ms / 60000)
    const seconds = Math.floor((ms % 60000) / 1000)
    return `${minutes}:${seconds.toString().padStart(2, "0")}`
  }

  const handleSearch = (value: string) => {
    if (value.trim()) {
      router.push(`/search/results?q=${encodeURIComponent(value.trim())}`)
    }
  }

  const handlePlayTrack = (track: any) => {
    const trackData = {
      id: track.id,
      title: track.title,
      artist: track.artist_name || "Unknown",
      image: track.cover_url,
      duration: track.duration_ms / 1000,
      audioUrl: track.audio_url,
    }
    if (currentTrack?.id === track.id) {
      togglePlay()
    } else {
      playTrack(trackData)
    }
  }

  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-4 flex items-center gap-4">
          <Link href="/search" className="text-foreground hover:text-primary">
            <ChevronLeft className="h-6 w-6" />
          </Link>
          <div className="flex-1">
            <input
              type="text"
              defaultValue={query}
              placeholder="Rechercher..."
              className="w-full rounded-full bg-secondary px-4 py-2 text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary"
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  handleSearch((e.target as HTMLInputElement).value)
                }
              }}
            />
          </div>
        </div>

        {isLoading ? (
          <div className="flex items-center justify-center py-16">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
          </div>
        ) : query ? (
          <>
            {/* Artists */}
            {artists.length > 0 && (
              <section className="mb-6">
                <h2 className="mb-3 text-lg font-semibold text-foreground">Artistes</h2>
                <div className="flex gap-4 overflow-x-auto pb-2">
                  {artists.map((artist: any) => (
                    <Link key={artist.id} href={`/artist/${artist.id}`}>
                      <div className="flex w-24 flex-col items-center gap-2">
                        <div className="relative h-24 w-24 overflow-hidden rounded-full">
                          <Image
                            src={artist.avatar_url || "/placeholder.svg?height=96&width=96&query=artist"}
                            alt={artist.name}
                            fill
                            className="object-cover"
                          />
                        </div>
                        <span className="text-center text-sm font-medium text-foreground">{artist.name}</span>
                      </div>
                    </Link>
                  ))}
                </div>
              </section>
            )}

            {/* Tracks */}
            {tracks.length > 0 && (
              <section className="mb-6">
                <h2 className="mb-3 text-lg font-semibold text-foreground">Titres</h2>
                <div className="space-y-1">
                  {tracks.map((track: any) => {
                    const isCurrentTrack = currentTrack?.id === track.id
                    const trackIsPlaying = isCurrentTrack && isPlaying

                    return (
                      <button
                        key={track.id}
                        onClick={() => handlePlayTrack(track)}
                        className={`flex w-full items-center gap-3 rounded-lg p-2 transition-colors hover:bg-secondary text-left ${isCurrentTrack ? "bg-secondary/50" : ""}`}
                      >
                        <div className="relative h-12 w-12 overflow-hidden rounded">
                          <Image
                            src={track.cover_url || "/placeholder.svg?height=48&width=48&query=music"}
                            alt={track.title}
                            fill
                            className="object-cover"
                          />
                          {trackIsPlaying && (
                            <div className="absolute inset-0 flex items-center justify-center bg-black/50">
                              <div className="flex gap-0.5">
                                <span className="h-3 w-0.5 animate-pulse bg-white" />
                                <span
                                  className="h-4 w-0.5 animate-pulse bg-white"
                                  style={{ animationDelay: "150ms" }}
                                />
                                <span
                                  className="h-2 w-0.5 animate-pulse bg-white"
                                  style={{ animationDelay: "300ms" }}
                                />
                              </div>
                            </div>
                          )}
                        </div>
                        <div className="flex-1">
                          <h3 className={`font-medium ${isCurrentTrack ? "text-primary" : "text-foreground"}`}>
                            {track.title}
                          </h3>
                          <p className="text-sm text-muted-foreground">{track.artist_name || "Unknown"}</p>
                        </div>
                        <span className="text-sm text-muted-foreground">{formatDuration(track.duration_ms || 0)}</span>
                      </button>
                    )
                  })}
                </div>
              </section>
            )}

            {/* Albums */}
            {albums.length > 0 && (
              <section className="mb-6">
                <h2 className="mb-3 text-lg font-semibold text-foreground">Albums</h2>
                <div className="flex gap-4 overflow-x-auto pb-2">
                  {albums.map((album: any) => (
                    <Link key={album.id} href={`/album/${album.id}`}>
                      <div className="w-32">
                        <div className="relative mb-2 aspect-square overflow-hidden rounded-lg">
                          <Image
                            src={album.cover_url || "/placeholder.svg?height=128&width=128&query=album"}
                            alt={album.title}
                            fill
                            className="object-cover"
                          />
                        </div>
                        <h3 className="text-sm font-medium text-foreground line-clamp-1">{album.title}</h3>
                        <p className="text-xs text-muted-foreground">
                          {album.artist_name} - {new Date(album.release_date).getFullYear()}
                        </p>
                      </div>
                    </Link>
                  ))}
                </div>
              </section>
            )}

            {/* Playlists */}
            {playlists.length > 0 && (
              <section className="mb-6">
                <h2 className="mb-3 text-lg font-semibold text-foreground">Playlists</h2>
                <div className="space-y-2">
                  {playlists.map((playlist: any) => (
                    <Link key={playlist.id} href={`/playlist/${playlist.id}`}>
                      <div className="flex items-center gap-3 rounded-lg p-2 transition-colors hover:bg-secondary">
                        <div className="relative h-14 w-14 overflow-hidden rounded">
                          <Image
                            src={playlist.cover_url || "/placeholder.svg?height=56&width=56&query=playlist"}
                            alt={playlist.name}
                            fill
                            className="object-cover"
                          />
                        </div>
                        <div className="flex-1">
                          <h3 className="font-medium text-foreground">{playlist.name}</h3>
                          <p className="text-sm text-muted-foreground">{playlist.total_tracks || 0} titres</p>
                        </div>
                        <Button size="icon" variant="ghost" className="h-10 w-10 rounded-full">
                          <Play className="h-5 w-5" />
                        </Button>
                      </div>
                    </Link>
                  ))}
                </div>
              </section>
            )}

            {/* No results */}
            {artists.length === 0 && tracks.length === 0 && albums.length === 0 && playlists.length === 0 && (
              <div className="flex flex-col items-center justify-center py-16 text-center">
                <p className="text-muted-foreground mb-2">Aucun resultat pour "{query}"</p>
                <p className="text-sm text-muted-foreground">Essayez avec d'autres mots-cles</p>
              </div>
            )}
          </>
        ) : (
          <div className="flex h-64 items-center justify-center">
            <p className="text-muted-foreground">Recherchez des artistes, titres, albums...</p>
          </div>
        )}
      </div>

      <BottomNav />
    </div>
  )
}

export default function SearchResultsPage() {
  return (
    <Suspense fallback={<div className="min-h-screen bg-background" />}>
      <SearchResultsContent />
    </Suspense>
  )
}
