import { sql, getPaginationValues } from "@/lib/db"
import { type NextRequest, NextResponse } from "next/server"

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const { page, limit, offset } = getPaginationValues({
      page: Number.parseInt(searchParams.get("page") || "1"),
      limit: Number.parseInt(searchParams.get("limit") || "20"),
    })
    const search = searchParams.get("search") || ""
    const userId = searchParams.get("user_id")
    const isEditorial = searchParams.get("editorial")
    const currentUserId = searchParams.get("current_user_id")

    console.log("[v0] Playlists API - Request params:", {
      search,
      userId,
      currentUserId,
      isEditorial,
      page,
      limit,
    })

    let playlists

    if (search && userId && isEditorial === "true" && currentUserId) {
      playlists = await sql`
        SELECT p.*, u.name as user_name, u.avatar_url as user_avatar,
               (SELECT COUNT(*) FROM playlist_tracks pt WHERE pt.playlist_id = p.id) as track_count
        FROM playlists p
        LEFT JOIN users u ON p.user_id = u.id
        WHERE p.name ILIKE ${`%${search}%`} 
          AND p.user_id = ${userId}
          AND p.is_editorial = TRUE
          AND (p.is_public = TRUE OR p.user_id = ${currentUserId})
        ORDER BY p.total_followers DESC
        LIMIT ${limit} OFFSET ${offset}
      `
    } else if (search && userId && currentUserId) {
      playlists = await sql`
        SELECT p.*, u.name as user_name, u.avatar_url as user_avatar,
               (SELECT COUNT(*) FROM playlist_tracks pt WHERE pt.playlist_id = p.id) as track_count
        FROM playlists p
        LEFT JOIN users u ON p.user_id = u.id
        WHERE p.name ILIKE ${`%${search}%`} 
          AND p.user_id = ${userId}
          AND (p.is_public = TRUE OR p.user_id = ${currentUserId})
        ORDER BY p.total_followers DESC
        LIMIT ${limit} OFFSET ${offset}
      `
    } else if (search && currentUserId) {
      playlists = await sql`
        SELECT p.*, u.name as user_name, u.avatar_url as user_avatar,
               (SELECT COUNT(*) FROM playlist_tracks pt WHERE pt.playlist_id = p.id) as track_count
        FROM playlists p
        LEFT JOIN users u ON p.user_id = u.id
        WHERE p.name ILIKE ${`%${search}%`}
          AND (p.is_public = TRUE OR p.user_id = ${currentUserId})
        ORDER BY p.total_followers DESC
        LIMIT ${limit} OFFSET ${offset}
      `
    } else if (userId && currentUserId) {
      playlists = await sql`
        SELECT p.*, u.name as user_name, u.avatar_url as user_avatar,
               (SELECT COUNT(*) FROM playlist_tracks pt WHERE pt.playlist_id = p.id) as track_count
        FROM playlists p
        LEFT JOIN users u ON p.user_id = u.id
        WHERE p.user_id = ${userId}
          AND (p.is_public = TRUE OR p.user_id = ${currentUserId})
        ORDER BY p.total_followers DESC
        LIMIT ${limit} OFFSET ${offset}
      `
    } else if (currentUserId) {
      playlists = await sql`
        SELECT p.*, u.name as user_name, u.avatar_url as user_avatar,
               (SELECT COUNT(*) FROM playlist_tracks pt WHERE pt.playlist_id = p.id) as track_count
        FROM playlists p
        LEFT JOIN users u ON p.user_id = u.id
        WHERE (p.is_public = TRUE OR p.user_id = ${currentUserId})
        ORDER BY p.total_followers DESC
        LIMIT ${limit} OFFSET ${offset}
      `
    } else {
      playlists = await sql`
        SELECT p.*, u.name as user_name, u.avatar_url as user_avatar,
               (SELECT COUNT(*) FROM playlist_tracks pt WHERE pt.playlist_id = p.id) as track_count
        FROM playlists p
        LEFT JOIN users u ON p.user_id = u.id
        WHERE p.is_public = TRUE
        ORDER BY p.total_followers DESC
        LIMIT ${limit} OFFSET ${offset}
      `
    }

    const playlistsWithTracks = await Promise.all(
      playlists.map(async (playlist: any) => {
        const tracks = await sql`
          SELECT t.id, t.title, t.audio_url, t.cover_url, t.duration_ms as duration,
                 a.name as artist_name, al.cover_url as album_cover
          FROM playlist_tracks pt
          JOIN tracks t ON pt.track_id = t.id
          LEFT JOIN artists a ON t.artist_id = a.id
          LEFT JOIN albums al ON t.album_id = al.id
          WHERE pt.playlist_id = ${playlist.id}
          ORDER BY pt.position ASC, pt.added_at DESC
          LIMIT 50
        `
        return {
          ...playlist,
          tracks: tracks,
        }
      }),
    )

    let countResult
    if (search && userId && isEditorial === "true" && currentUserId) {
      countResult = await sql`
        SELECT COUNT(*) as total FROM playlists p 
        WHERE p.name ILIKE ${`%${search}%`} 
          AND p.user_id = ${userId}
          AND p.is_editorial = TRUE
          AND (p.is_public = TRUE OR p.user_id = ${currentUserId})
      `
    } else if (search && userId && currentUserId) {
      countResult = await sql`
        SELECT COUNT(*) as total FROM playlists p 
        WHERE p.name ILIKE ${`%${search}%`} 
          AND p.user_id = ${userId}
          AND (p.is_public = TRUE OR p.user_id = ${currentUserId})
      `
    } else if (search && currentUserId) {
      countResult = await sql`
        SELECT COUNT(*) as total FROM playlists p 
        WHERE p.name ILIKE ${`%${search}%`}
          AND (p.is_public = TRUE OR p.user_id = ${currentUserId})
      `
    } else if (userId && currentUserId) {
      countResult = await sql`
        SELECT COUNT(*) as total FROM playlists p 
        WHERE p.user_id = ${userId}
          AND (p.is_public = TRUE OR p.user_id = ${currentUserId})
      `
    } else if (currentUserId) {
      countResult = await sql`
        SELECT COUNT(*) as total FROM playlists p 
        WHERE (p.is_public = TRUE OR p.user_id = ${currentUserId})
      `
    } else {
      countResult = await sql`
        SELECT COUNT(*) as total FROM playlists p WHERE p.is_public = TRUE
      `
    }

    const total = Number.parseInt(countResult[0].total)

    console.log("[v0] Playlists API - Response:", {
      count: playlistsWithTracks.length,
      total,
      page,
      userId,
      currentUserId,
      playlists: playlistsWithTracks.map((p) => ({
        id: p.id,
        name: p.name,
        is_public: p.is_public,
        user_id: p.user_id,
        track_count: p.tracks?.length || 0,
      })),
    })

    return NextResponse.json({
      data: playlistsWithTracks,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    })
  } catch (error) {
    console.error("[v0] Get playlists error:", error)
    return NextResponse.json({ error: "Erreur lors de la récupération des playlists" }, { status: 500 })
  }
}

export async function POST(request: NextRequest) {
  try {
    const data = await request.json()

    const {
      name,
      description,
      cover_url,
      is_public = true,
      is_collaborative = false,
      is_editorial = false,
      track_ids,
    } = data

    const user_id = data.user_id || data.userId

    if (!name || name.trim().length === 0) {
      return NextResponse.json({ error: "Le nom est requis" }, { status: 400 })
    }

    if (name.length > 255) {
      return NextResponse.json({ error: "Le nom est trop long (max 255 caractères)" }, { status: 400 })
    }

    if (!user_id) {
      return NextResponse.json({ error: "Authentification requise" }, { status: 401 })
    }

    const users = await sql`SELECT id FROM users WHERE id = ${user_id}`
    if (users.length === 0) {
      return NextResponse.json({ error: "Utilisateur non trouvé" }, { status: 404 })
    }

    const playlists = await sql`
      INSERT INTO playlists (name, description, cover_url, user_id, 
                            is_public, is_collaborative, is_editorial, total_tracks)
      VALUES (${name.trim()}, ${description?.trim() || null}, ${cover_url || null}, ${user_id},
              ${is_public}, ${is_collaborative}, ${is_editorial}, ${0})
      RETURNING *
    `

    const playlist = playlists[0]

    if (track_ids && Array.isArray(track_ids) && track_ids.length > 0) {
      // Validate each track individually instead of using ANY
      const validTrackIds = []

      for (const trackId of track_ids) {
        const trackCheck = await sql`
          SELECT id FROM tracks WHERE id = ${trackId} AND status = 'published'
        `
        if (trackCheck.length > 0) {
          validTrackIds.push(trackId)
        }
      }

      if (validTrackIds.length !== track_ids.length) {
        console.warn(
          `[v0] Some tracks not found or not published. Expected: ${track_ids.length}, Found: ${validTrackIds.length}`,
        )
      }

      // Insert tracks one by one
      for (let i = 0; i < validTrackIds.length; i++) {
        await sql`
          INSERT INTO playlist_tracks (playlist_id, track_id, position, added_by)
          VALUES (${playlist.id}, ${validTrackIds[i]}, ${i}, ${user_id})
          ON CONFLICT (playlist_id, track_id) DO NOTHING
        `
      }

      // Update total tracks count
      await sql`
        UPDATE playlists 
        SET total_tracks = ${validTrackIds.length}
        WHERE id = ${playlist.id}
      `
    }

    console.log("[v0] Created playlist:", { id: playlist.id, name, tracks: track_ids?.length || 0 })

    return NextResponse.json({ data: playlist }, { status: 201 })
  } catch (error) {
    console.error("[v0] Create playlist error:", error)
    return NextResponse.json({ error: "Erreur lors de la création de la playlist" }, { status: 500 })
  }
}
