import { NextResponse } from "next/server"
import { sql } from "@/lib/db"

export async function GET() {
  try {
    console.log("[v0] Dashboard API - Fetching data from database")

    // Get total users
    const usersResult = await sql`SELECT COUNT(*) as count FROM users`
    const totalUsers = Number.parseInt(usersResult[0]?.count || "0")

    // Get new users this month
    const newUsersResult = await sql`
      SELECT COUNT(*) as count FROM users 
      WHERE created_at >= DATE_TRUNC('month', CURRENT_DATE)
    `
    const newUsersThisMonth = Number.parseInt(newUsersResult[0]?.count || "0")

    // Get total tracks
    const tracksResult = await sql`SELECT COUNT(*) as count FROM tracks`
    const totalTracks = Number.parseInt(tracksResult[0]?.count || "0")

    // Get new tracks this month
    const newTracksResult = await sql`
      SELECT COUNT(*) as count FROM tracks 
      WHERE created_at >= DATE_TRUNC('month', CURRENT_DATE)
    `
    const newTracksThisMonth = Number.parseInt(newTracksResult[0]?.count || "0")

    const streamsResult = await sql`SELECT COALESCE(SUM(total_streams), 0) as count FROM tracks`
    const totalStreams = Number.parseInt(streamsResult[0]?.count || "0")

    // Get premium users count (active subscriptions)
    const premiumResult = await sql`
      SELECT COUNT(*) as count FROM user_subscriptions 
      WHERE status = 'active'
    `
    const premiumUsers = Number.parseInt(premiumResult[0]?.count || "0")

    const revenueResult = await sql`
      SELECT COALESCE(SUM(amount), 0) as total FROM payment_transactions 
      WHERE status = 'completed' 
      AND created_at >= DATE_TRUNC('month', CURRENT_DATE)
    `
    const monthlyRevenue = Number.parseInt(revenueResult[0]?.total || "0")

    const lastMonthRevenueResult = await sql`
      SELECT COALESCE(SUM(amount), 0) as total FROM payment_transactions 
      WHERE status = 'completed' 
      AND created_at >= DATE_TRUNC('month', CURRENT_DATE - INTERVAL '1 month')
      AND created_at < DATE_TRUNC('month', CURRENT_DATE)
    `
    const lastMonthRevenue = Number.parseInt(lastMonthRevenueResult[0]?.total || "0")
    const revenueChange =
      lastMonthRevenue > 0 ? Math.round(((monthlyRevenue - lastMonthRevenue) / lastMonthRevenue) * 100) : 0

    const currentMonthStreamsResult = await sql`
      SELECT COUNT(*) as count FROM listening_history 
      WHERE played_at >= DATE_TRUNC('month', CURRENT_DATE)
    `
    const currentMonthStreams = Number.parseInt(currentMonthStreamsResult[0]?.count || "0")

    const lastMonthStreamsResult = await sql`
      SELECT COUNT(*) as count FROM listening_history 
      WHERE played_at >= DATE_TRUNC('month', CURRENT_DATE - INTERVAL '1 month')
      AND played_at < DATE_TRUNC('month', CURRENT_DATE)
    `
    const lastMonthStreams = Number.parseInt(lastMonthStreamsResult[0]?.count || "0")
    const streamsChange =
      lastMonthStreams > 0 ? Math.round(((currentMonthStreams - lastMonthStreams) / lastMonthStreams) * 100) : 0

    const topTracks = await sql`
      SELECT t.id, t.title, t.total_streams, t.cover_url,
             a.name as artist_name
      FROM tracks t
      LEFT JOIN artists a ON t.artist_id = a.id
      ORDER BY t.total_streams DESC NULLS LAST
      LIMIT 5
    `

    // Get recent users
    const recentUsers = await sql`
      SELECT id, name, email, avatar_url, subscription_type, created_at
      FROM users
      ORDER BY created_at DESC
      LIMIT 5
    `

    const recentActivity = await sql`
      SELECT action, details, created_at
      FROM admin_logs
      ORDER BY created_at DESC
      LIMIT 5
    `

    return NextResponse.json({
      stats: {
        totalUsers,
        newUsersThisMonth,
        totalTracks,
        newTracksThisMonth,
        totalStreams,
        premiumUsers,
        monthlyRevenue,
        revenueChange,
        streamsChange,
      },
      topTracks: topTracks.map((t: any) => ({
        id: t.id,
        title: t.title,
        artist: t.artist_name || "Unknown",
        plays: t.total_streams || 0,
        image: t.cover_url || "/placeholder.svg?height=48&width=48",
      })),
      recentUsers: recentUsers.map((u: any) => ({
        id: u.id,
        name: u.name,
        email: u.email,
        avatar: u.avatar_url || "/placeholder.svg?height=32&width=32",
        status: u.subscription_type === "free" ? "Free" : "Premium",
        date: formatTimeAgo(u.created_at),
      })),
      recentActivity:
        recentActivity.length > 0
          ? recentActivity.map((a: any) => ({
              type: a.action,
              message: a.details?.message || a.action,
              time: formatTimeAgo(a.created_at),
            }))
          : [{ type: "info", message: "Aucune activité récente", time: "Maintenant" }],
    })
  } catch (error: any) {
    console.error("[v0] Dashboard error:", error)

    // Check if it's a database configuration error
    if (error.message?.includes("Database not configured")) {
      return NextResponse.json(
        {
          error: "Database not configured",
          message: "Please configure DATABASE_URL environment variable",
          stats: {
            totalUsers: 0,
            newUsersThisMonth: 0,
            totalTracks: 0,
            newTracksThisMonth: 0,
            totalStreams: 0,
            premiumUsers: 0,
            monthlyRevenue: 0,
            revenueChange: 0,
            streamsChange: 0,
          },
          topTracks: [],
          recentUsers: [],
          recentActivity: [{ type: "warning", message: "Base de données non configurée", time: "Maintenant" }],
        },
        { status: 200 },
      )
    }

    return NextResponse.json({ error: "Failed to fetch dashboard data" }, { status: 500 })
  }
}

function formatTimeAgo(date: Date | string): string {
  const now = new Date()
  const past = new Date(date)
  const diffMs = now.getTime() - past.getTime()
  const diffMins = Math.floor(diffMs / 60000)
  const diffHours = Math.floor(diffMs / 3600000)
  const diffDays = Math.floor(diffMs / 86400000)

  if (diffMins < 1) return "À l'instant"
  if (diffMins < 60) return `Il y a ${diffMins} min`
  if (diffHours < 24) return `Il y a ${diffHours}h`
  if (diffDays < 7) return `Il y a ${diffDays}j`
  return past.toLocaleDateString("fr-FR")
}
