"use client"

import { useState } from "react"
import Image from "next/image"
import { ChevronLeft, Mic, Loader2, Video, Play } from "lucide-react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { BottomNav } from "@/components/bottom-nav"
import { SearchBar } from "@/components/search-bar"
import { SearchChip } from "@/components/search-chip"
import { SectionHeader } from "@/components/section-header"
import useSWR from "swr"

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

export default function SearchPage() {
  const router = useRouter()
  const [searchQuery, setSearchQuery] = useState("")

  // Fetch genres from database
  const { data: genresData, isLoading: genresLoading } = useSWR("/api/genres", fetcher)

  // Fetch popular artists
  const { data: artistsData, isLoading: artistsLoading } = useSWR("/api/artists?limit=8", fetcher)

  // Fetch latest videos
  const { data: videosData, isLoading: videosLoading } = useSWR("/api/videos?limit=4", fetcher)

  const genres = genresData?.genres || genresData?.data || []
  const artists = artistsData?.artists || artistsData?.data || []
  const videos = videosData?.videos || []

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

  const genreColors = [
    "bg-amber-500",
    "bg-cyan-500",
    "bg-indigo-500",
    "bg-pink-500",
    "bg-blue-500",
    "bg-orange-500",
    "bg-purple-500",
    "bg-teal-500",
  ]

  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 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">Rechercher</h1>
        </div>

        {/* Search Bar */}
        <div className="mb-6">
          <SearchBar value={searchQuery} onChange={handleSearch} />
        </div>

        {/* Recent Searches - Will be populated from user history later */}
        <div className="mb-6 flex flex-wrap gap-2">
          <SearchChip label="Afrobeat" href="/search/results?q=Afrobeat" />
          <SearchChip label="Hip-Hop" href="/search/results?q=Hip-Hop" />
          <SearchChip label="R&B" href="/search/results?q=R%26B" />
          <SearchChip label="Pop" href="/search/results?q=Pop" />
        </div>

        {/* Genres */}
        <section className="mb-8">
          <SectionHeader title="Parcourir par genre" />
          <div className="mt-4 grid grid-cols-4 gap-4">
            {genresLoading ? (
              <div className="col-span-4 flex items-center justify-center py-8">
                <Loader2 className="h-6 w-6 animate-spin text-primary" />
              </div>
            ) : genres.length > 0 ? (
              genres.slice(0, 8).map((genre: any, index: number) => (
                <Link key={genre.id} href={`/genre/${genre.id}`}>
                  <div
                    className={`relative h-16 w-16 overflow-hidden rounded-2xl transition-transform hover:scale-105 ${genreColors[index % genreColors.length]}`}
                  >
                    {genre.icon_url ? (
                      <Image
                        src={genre.icon_url || "/placeholder.svg"}
                        alt={genre.name}
                        fill
                        className="object-cover mix-blend-overlay opacity-80"
                      />
                    ) : (
                      <div className="flex items-center justify-center h-full">
                        <span className="text-white text-xs font-bold text-center px-1">{genre.name}</span>
                      </div>
                    )}
                  </div>
                  <p className="text-xs text-center mt-1 text-muted-foreground truncate">{genre.name}</p>
                </Link>
              ))
            ) : (
              <p className="col-span-4 text-center text-muted-foreground">Aucun genre disponible</p>
            )}
          </div>
        </section>

        {/* Videos Section */}
        <section className="mb-8">
          <SectionHeader title="Vidéos" href="/videos" />
          <div className="mt-4 grid grid-cols-2 gap-4">
            {videosLoading ? (
              <div className="col-span-2 flex items-center justify-center py-8">
                <Loader2 className="h-6 w-6 animate-spin text-primary" />
              </div>
            ) : videos.length > 0 ? (
              videos.slice(0, 4).map((video: any) => (
                <Link key={video.id} href={`/videos/${video.id}`} className="group">
                  <div className="relative aspect-video overflow-hidden rounded-lg bg-muted">
                    {video.thumbnail_url ? (
                      <Image
                        src={video.thumbnail_url}
                        alt={video.title}
                        fill
                        className="object-cover transition-transform group-hover:scale-105"
                      />
                    ) : (
                      <div className="flex h-full w-full items-center justify-center bg-gradient-to-br from-primary/20 to-primary/5">
                        <Video className="h-8 w-8 text-muted-foreground" />
                      </div>
                    )}
                    <div className="absolute inset-0 flex items-center justify-center bg-black/0 transition-colors group-hover:bg-black/30">
                      <div className="scale-0 rounded-full bg-primary p-2 transition-transform group-hover:scale-100">
                        <Play className="h-4 w-4 fill-primary-foreground text-primary-foreground" />
                      </div>
                    </div>
                    {!video.is_free && (
                      <span className="absolute left-2 top-2 rounded bg-primary px-1.5 py-0.5 text-[10px] font-medium text-primary-foreground">
                        {video.price_fcfa} FCFA
                      </span>
                    )}
                  </div>
                  <p className="mt-1 truncate text-xs font-medium text-foreground">{video.title}</p>
                  {video.artist_name && (
                    <p className="truncate text-[10px] text-muted-foreground">{video.artist_name}</p>
                  )}
                </Link>
              ))
            ) : (
              <Link href="/videos" className="col-span-2 flex flex-col items-center justify-center rounded-lg border border-dashed border-border py-8 text-center hover:border-primary">
                <Video className="mb-2 h-8 w-8 text-muted-foreground" />
                <p className="text-sm text-muted-foreground">Découvrir les vidéos</p>
              </Link>
            )}
          </div>
        </section>

        {/* Voice Search */}
        <div className="mb-8 flex justify-center">
          <button className="flex h-16 w-16 items-center justify-center rounded-full bg-primary text-primary-foreground transition-transform hover:scale-105">
            <Mic className="h-6 w-6" />
          </button>
        </div>

        {/* Popular Artists */}
        <section className="mb-8">
          <SectionHeader title="Artistes populaires" />
          <div className="mt-4 grid grid-cols-4 gap-4">
            {artistsLoading ? (
              <div className="col-span-4 flex items-center justify-center py-8">
                <Loader2 className="h-6 w-6 animate-spin text-primary" />
              </div>
            ) : artists.length > 0 ? (
              artists.slice(0, 8).map((artist: any) => (
                <Link key={artist.id} href={`/artist/${artist.id}`}>
                  <div className="relative h-16 w-16 overflow-hidden rounded-full transition-transform hover:scale-105">
                    <Image
                      src={artist.avatar_url || "/placeholder.svg?height=64&width=64&query=artist"}
                      alt={artist.name}
                      fill
                      className="object-cover"
                    />
                  </div>
                  <p className="text-xs text-center mt-1 text-muted-foreground truncate">{artist.name}</p>
                </Link>
              ))
            ) : (
              <p className="col-span-4 text-center text-muted-foreground">Aucun artiste disponible</p>
            )}
          </div>
        </section>
      </div>

      <BottomNav />
    </div>
  )
}
