"use client"

import { BottomNav } from "@/components/bottom-nav"
import { SectionHeader } from "@/components/section-header"
import { AlbumCard } from "@/components/album-card"
import { MixCard } from "@/components/mix-card"
import { usePlayer } from "@/components/player-provider"
import { useAuth } from "@/components/auth-provider"
import Link from "next/link"
import Image from "next/image"
import { Play, Settings, Mic2, Loader2, Plus } from "lucide-react"
import { useRouter } from "next/navigation"
import { useEffect } from "react"
import useSWR from "swr"
import { toast } from "sonner"
import { getImageUrl } from "@/lib/image-utils"

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

interface TrackData {
  id: string
  title: string
  artist_name: string
  artist_id?: string // Added artist_id field
  cover_url?: string
  album_cover?: string
  audio_url?: string
  duration?: number
  album_id?: string
  created_at?: string
}

interface AlbumData {
  id: string
  title: string
  artist_name: string
  cover_url?: string
  release_date?: string
  created_at?: string
}

export default function HomePage() {
  const { recentlyPlayed: recentTracks, playTrack, currentTrack, isPlaying, togglePlay } = usePlayer()
  const { user, isAuthenticated } = useAuth()
  const router = useRouter()

  const { data: albumsData, isLoading: albumsLoading } = useSWR("/api/albums?status=published&limit=20", fetcher)
  const { data: tracksData, isLoading: tracksLoading } = useSWR("/api/tracks?status=published&limit=20", fetcher)
  const {
    data: userMixesData,
    isLoading: mixesLoading,
    mutate: mutateMixes,
  } = useSWR(user?.id ? `/api/playlists?user_id=${user.id}&current_user_id=${user.id}&limit=10` : null, fetcher)

  useEffect(() => {
    if (!isAuthenticated) {
      router.push("/")
    }
  }, [isAuthenticated, router])

  const albums: AlbumData[] = albumsData?.data || []
  const tracks: TrackData[] = tracksData?.data || []
  const userMixes = userMixesData?.data || []

  const toPlayerTrack = (t: TrackData) => ({
    id: t.id,
    title: t.title,
    artist: t.artist_name,
    artistId: t.artist_id, // Include artistId for navigation to artist pages
    image: getImageUrl(t.cover_url || t.album_cover, "track"),
    cover_url: t.cover_url, // Preserve original cover_url from database
    album_cover: t.album_cover, // Preserve original album_cover from database
    duration: t.duration || 0,
    audioUrl: t.audio_url,
  })

  const newReleases = [
    ...albums.map((a) => ({
      id: a.id,
      title: a.title,
      image: getImageUrl(a.cover_url, "album"),
      type: "album" as const,
      artist: a.artist_name,
      date: a.created_at || a.release_date || "",
    })),
    ...tracks
      .filter((t) => !t.album_id)
      .map((t) => ({
        id: t.id,
        title: t.title,
        image: getImageUrl(t.cover_url || t.album_cover, "track"),
        type: "track" as const,
        artist: t.artist_name,
        date: t.created_at || "",
        track: toPlayerTrack(t),
      })),
  ]
    .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
    .slice(0, 10)

  const displayRecent =
    recentTracks.length > 0
      ? recentTracks.slice(0, 3).map((t) => ({
          id: t.id,
          title: t.title,
          // Use cover_url/album_cover from track if available, fallback to image
          image: getImageUrl(t.cover_url || t.album_cover || t.image, "track"),
          type: "track" as const,
          track: t, // Already in correct format
        }))
      : tracks.slice(0, 3).map((t) => ({
          id: t.id,
          title: t.title,
          image: getImageUrl(t.cover_url || t.album_cover, "track"),
          type: "track" as const,
          track: toPlayerTrack(t),
        }))

  const firstName = user?.name?.split(" ")[0] || "Clara"

  const handleDeleteMix = async (mixId: string) => {
    try {
      const response = await fetch(`/api/playlists/${mixId}`, {
        method: "DELETE",
      })
      if (!response.ok) throw new Error("Failed to delete")
      toast.success("Mix supprimé avec succès")
      mutateMixes()
    } catch (error) {
      toast.error("Erreur lors de la suppression du mix")
    }
  }

  const handleEditMix = (mixId: string) => {
    router.push(`/mix/${mixId}/edit`)
  }

  if (!isAuthenticated) {
    return null
  }

  const isLoading = albumsLoading || tracksLoading

  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">
          <h1 className="text-2xl font-bold text-foreground">Bonjour, {firstName}!</h1>
          <div className="flex items-center gap-2">
            {user?.role === "artist" && (
              <Link
                href="/artist"
                className="flex h-10 w-10 items-center justify-center rounded-full bg-purple-500/20 text-purple-400"
              >
                <Mic2 className="h-5 w-5" />
              </Link>
            )}
            {user?.role === "admin" && (
              <Link
                href="/admin"
                className="flex h-10 w-10 items-center justify-center rounded-full bg-purple-500/20 text-purple-400"
              >
                <Settings className="h-5 w-5" />
              </Link>
            )}
            <Link href="/profile">
              <div className="h-10 w-10 overflow-hidden rounded-full bg-secondary">
                <Image
                  src={getImageUrl(user?.avatar, "user")}
                  alt="Profile"
                  width={40}
                  height={40}
                  className="object-cover"
                />
              </div>
            </Link>
          </div>
        </div>

        {/* Recently Played */}
        <section className="mb-8">
          <SectionHeader title="Derniers Écoutés" href="/library/recent" />
          <div className="mt-4 flex gap-4 overflow-x-auto pb-2">
            {isLoading ? (
              <div className="flex items-center justify-center w-full py-8">
                <Loader2 className="w-6 h-6 animate-spin text-purple-500" />
              </div>
            ) : displayRecent.length > 0 ? (
              displayRecent.map((item) => (
                <AlbumCard
                  key={item.id}
                  id={item.id}
                  title={item.title}
                  image={item.image}
                  href={`/track/${item.id}`}
                  track={item.track}
                />
              ))
            ) : (
              <p className="text-muted-foreground text-sm">Aucune écoute récente</p>
            )}
          </div>
        </section>

        {/* Quick Play - Currently Playing */}
        {currentTrack && (
          <section className="mb-8">
            <h2 className="mb-3 text-sm font-semibold text-muted-foreground">CONTINUER L{"'"}ÉCOUTE</h2>
            <button
              onClick={togglePlay}
              className="flex w-full items-center gap-4 rounded-xl bg-secondary/50 p-4 transition-colors hover:bg-secondary"
            >
              <div className="relative h-16 w-16 overflow-hidden rounded-lg">
                <Image
                  src={getImageUrl(currentTrack.cover_url || currentTrack.album_cover || currentTrack.image, "track")}
                  alt={currentTrack.title}
                  fill
                  className="object-cover"
                />
                {isPlaying && (
                  <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 text-left">
                <p className="font-medium text-foreground">{currentTrack.title}</p>
                <p className="text-sm text-muted-foreground">{currentTrack.artist}</p>
              </div>
              <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary text-primary-foreground">
                <Play className={`h-5 w-5 ${isPlaying ? "hidden" : ""} ml-0.5`} />
                {isPlaying && (
                  <div className="flex gap-0.5">
                    <span className="h-3 w-0.5 animate-pulse bg-primary-foreground" />
                    <span
                      className="h-4 w-0.5 animate-pulse bg-primary-foreground"
                      style={{ animationDelay: "150ms" }}
                    />
                    <span
                      className="h-2 w-0.5 animate-pulse bg-primary-foreground"
                      style={{ animationDelay: "300ms" }}
                    />
                  </div>
                )}
              </div>
            </button>
          </section>
        )}

        <section className="mb-8">
          <div className="flex items-center justify-between">
            <SectionHeader title="Mes Mix Personnalisés" href="/mixes" />
            <Link
              href="/mix/create"
              className="flex h-8 w-8 items-center justify-center rounded-full bg-primary text-primary-foreground"
            >
              <Plus className="h-4 w-4" />
            </Link>
          </div>
          <div className="mt-4 flex gap-4 overflow-x-auto pb-2">
            {mixesLoading ? (
              <div className="flex items-center justify-center w-full py-8">
                <Loader2 className="w-6 h-6 animate-spin text-purple-500" />
              </div>
            ) : userMixes.length > 0 ? (
              userMixes.map((mix: { id: string; name: string; cover_url?: string; tracks?: any[] }) => (
                <MixCard
                  key={mix.id}
                  id={mix.id}
                  title={mix.name}
                  image={getImageUrl(mix.cover_url, "playlist")}
                  href={`/mix/${mix.id}`}
                  tracks={mix.tracks || []}
                  canManage={true}
                  onDelete={handleDeleteMix}
                  onEdit={handleEditMix}
                />
              ))
            ) : (
              <div className="flex flex-col items-center justify-center w-full py-8 text-center">
                <p className="text-muted-foreground text-sm mb-2">Vous n'avez pas encore de mix</p>
                <Link href="/mix/create" className="text-primary text-sm hover:underline">
                  Créer votre premier mix
                </Link>
              </div>
            )}
          </div>
        </section>

        {/* New Releases - From Database */}
        <section className="mb-8">
          <SectionHeader title="Nouveautés" href="/new-releases" />
          <div className="mt-4 flex gap-4 overflow-x-auto pb-2">
            {isLoading ? (
              <div className="flex items-center justify-center w-full py-8">
                <Loader2 className="w-6 h-6 animate-spin text-purple-500" />
              </div>
            ) : newReleases.length > 0 ? (
              newReleases.map((item) => (
                <AlbumCard
                  key={`${item.type}-${item.id}`}
                  id={item.id}
                  title={item.title}
                  artist={item.artist}
                  image={item.image}
                  href={item.type === "album" ? `/album/${item.id}` : `/track/${item.id}`}
                  size="sm"
                  track={item.type === "track" && "track" in item ? item.track : undefined}
                />
              ))
            ) : (
              <p className="text-muted-foreground text-sm">Aucune nouveauté pour le moment</p>
            )}
          </div>
        </section>
      </div>

      <BottomNav />
    </div>
  )
}
