"use client"

import { useState } from "react"
import { Play, Users, Clock, Globe, Calendar, Loader2 } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { useAuth } from "@/components/auth-provider"
import useSWR from "swr"

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

export default function ArtistAnalyticsPage() {
  const { user } = useAuth()
  const artistId = user?.artistId
  const [period, setPeriod] = useState("7d")

  const { data, isLoading } = useSWR(
    artistId ? `/api/artist/analytics?artistId=${artistId}&period=${period}` : null,
    fetcher,
  )

  const formatNumber = (num: number) => {
    if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`
    if (num >= 1000) return `${(num / 1000).toFixed(1)}K`
    return num.toString()
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-purple-500" />
      </div>
    )
  }

  const streamData = data?.streamsOverTime || []
  const topTracks = data?.topTracks || []
  const topCountries = data?.topCountries || []
  const totalStreams = data?.totalStreams || 0
  const uniqueListeners = data?.uniqueListeners || 0

  const maxStreams = streamData.length > 0 ? Math.max(...streamData.map((d: any) => d.streams)) : 1

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">Statistiques</h1>
          <p className="text-zinc-400">Analysez vos performances</p>
        </div>
        <Select value={period} onValueChange={setPeriod}>
          <SelectTrigger className="w-40 bg-zinc-800/50 border-zinc-700 text-white">
            <Calendar className="w-4 h-4 mr-2" />
            <SelectValue />
          </SelectTrigger>
          <SelectContent className="bg-zinc-800 border-zinc-700">
            <SelectItem value="7d">7 derniers jours</SelectItem>
            <SelectItem value="30d">30 derniers jours</SelectItem>
            <SelectItem value="90d">3 derniers mois</SelectItem>
            <SelectItem value="1y">Cette annee</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Overview Stats */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-purple-500/20 rounded-lg flex items-center justify-center">
                <Play className="w-5 h-5 text-purple-400" />
              </div>
              <div>
                <p className="text-zinc-400 text-sm">Total streams</p>
                <p className="text-xl font-bold text-white">{formatNumber(totalStreams)}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-blue-500/20 rounded-lg flex items-center justify-center">
                <Users className="w-5 h-5 text-blue-400" />
              </div>
              <div>
                <p className="text-zinc-400 text-sm">Auditeurs</p>
                <p className="text-xl font-bold text-white">{formatNumber(uniqueListeners)}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-green-500/20 rounded-lg flex items-center justify-center">
                <Clock className="w-5 h-5 text-green-400" />
              </div>
              <div>
                <p className="text-zinc-400 text-sm">Titres</p>
                <p className="text-xl font-bold text-white">{topTracks.length}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-pink-500/20 rounded-lg flex items-center justify-center">
                <Globe className="w-5 h-5 text-pink-400" />
              </div>
              <div>
                <p className="text-zinc-400 text-sm">Pays</p>
                <p className="text-xl font-bold text-white">{topCountries.length}</p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Charts */}
      <div className="grid lg:grid-cols-2 gap-6">
        {/* Streams Chart */}
        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardHeader>
            <CardTitle className="text-white">Streams par jour</CardTitle>
          </CardHeader>
          <CardContent>
            {streamData.length === 0 ? (
              <div className="h-64 flex items-center justify-center text-zinc-400">Pas de donnees disponibles</div>
            ) : (
              <div className="h-64 flex items-end justify-between gap-2">
                {streamData.map((day: any, index: number) => (
                  <div key={index} className="flex-1 flex flex-col items-center gap-2">
                    <div
                      className="w-full bg-gradient-to-t from-purple-600 to-pink-500 rounded-t-lg transition-all hover:opacity-80"
                      style={{ height: `${(day.streams / maxStreams) * 100}%`, minHeight: "4px" }}
                    ></div>
                    <span className="text-zinc-400 text-xs">
                      {new Date(day.date).toLocaleDateString("fr-FR", { weekday: "short" })}
                    </span>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Top Countries */}
        <Card className="bg-zinc-800/50 border-zinc-700">
          <CardHeader>
            <CardTitle className="text-white">Top pays</CardTitle>
          </CardHeader>
          <CardContent>
            {topCountries.length === 0 ? (
              <div className="h-64 flex items-center justify-center text-zinc-400">Pas de donnees disponibles</div>
            ) : (
              <div className="space-y-4">
                {topCountries.map((country: any, index: number) => {
                  const maxListeners = Math.max(...topCountries.map((c: any) => c.listeners))
                  return (
                    <div key={index} className="space-y-2">
                      <div className="flex items-center justify-between">
                        <span className="text-white">{country.country}</span>
                        <span className="text-zinc-400 text-sm">{formatNumber(country.listeners)}</span>
                      </div>
                      <div className="h-2 bg-zinc-700 rounded-full overflow-hidden">
                        <div
                          className="h-full bg-gradient-to-r from-purple-600 to-pink-500 rounded-full"
                          style={{ width: `${(country.listeners / maxListeners) * 100}%` }}
                        ></div>
                      </div>
                    </div>
                  )
                })}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Top Tracks */}
      <Card className="bg-zinc-800/50 border-zinc-700">
        <CardHeader>
          <CardTitle className="text-white">Titres les plus ecoutes</CardTitle>
        </CardHeader>
        <CardContent>
          {topTracks.length === 0 ? (
            <div className="text-center py-8 text-zinc-400">Aucun titre pour le moment</div>
          ) : (
            <div className="space-y-4">
              {topTracks.map((track: any, index: number) => (
                <div key={index} className="flex items-center gap-4">
                  <span className="text-zinc-500 w-6 text-center">{index + 1}</span>
                  <img
                    src={track.cover_url || "/placeholder.svg?height=48&width=48&query=music"}
                    alt={track.title}
                    className="w-12 h-12 rounded object-cover"
                  />
                  <div className="flex-1">
                    <p className="text-white font-medium">{track.title}</p>
                    <p className="text-zinc-400 text-sm">{formatNumber(track.play_count || 0)} streams</p>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
