"use client"

import { Edit, Share2, Globe, Instagram, Twitter, Youtube, Users, Play, Music, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import Link from "next/link"
import { useAuth } from "@/components/auth-provider"
import { usePlayer } from "@/components/player-provider"
import { VerifiedBadge } from "@/components/verified-badge"
import useSWR from "swr"

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

export default function ArtistProfilePreviewPage() {
  const { user } = useAuth()
  const { playTrack, currentTrack, isPlaying, togglePlay } = usePlayer()
  const artistId = user?.artistId

  const { data: artist, isLoading: loadingArtist } = useSWR(artistId ? `/api/artists/${artistId}` : null, fetcher, {
    dedupingInterval: 60000,
    errorRetryCount: 2,
  })

  const { data: tracksData, isLoading: loadingTracks } = useSWR(
    artistId ? `/api/tracks?artist_id=${artistId}&status=published` : null,
    fetcher,
    { dedupingInterval: 60000, errorRetryCount: 2 },
  )

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

  const formatDuration = (ms: number) => {
    const minutes = Math.floor(ms / 60000)
    const seconds = Math.floor((ms % 60000) / 1000)
    return `${minutes}:${seconds.toString().padStart(2, "0")}`
  }

  const handlePlayTrack = (track: any) => {
    if (currentTrack?.id === track.id) {
      togglePlay()
    } else {
      playTrack({
        id: track.id,
        title: track.title,
        artist: artist?.name || user?.name || "Unknown",
        image: track.cover_url || "/abstract-music-album.png",
        cover_url: track.cover_url,
        album_cover: track.album_cover,
        audioUrl: track.audio_url,
        duration: track.duration_ms ? track.duration_ms / 1000 : 0,
      })
    }
  }

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

  const tracks = tracksData?.data || []
  const socialLinks = artist?.social_links || {}

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Apercu du profil public</h1>
          <p className="text-zinc-400">Voici comment les utilisateurs voient votre profil</p>
        </div>
        <Link href="/artist/settings">
          <Button variant="outline" className="border-zinc-700 bg-transparent">
            <Edit className="w-4 h-4 mr-2" />
            Modifier le profil
          </Button>
        </Link>
      </div>

      {/* Profile Preview */}
      <Card className="bg-zinc-800/30 border-zinc-700/50 overflow-hidden">
        {/* Cover */}
        <div className="h-48 relative">
          <img
            src={artist?.cover_url || "/placeholder.svg?height=192&width=800&query=music cover gradient"}
            alt="Cover"
            className="w-full h-full object-cover"
          />
          <div className="absolute inset-0 bg-gradient-to-t from-zinc-900 to-transparent" />
        </div>

        {/* Profile Info */}
        <CardContent className="relative -mt-16 px-6 pb-6">
          <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-end">
            <img
              src={artist?.avatar_url || "/placeholder.svg?height=128&width=128&query=artist portrait"}
              alt={artist?.name || user?.name}
              className="w-32 h-32 rounded-full border-4 border-zinc-900 object-cover"
            />
            <div className="flex-1">
              <div className="flex items-center gap-2 mb-1">
                <h2 className="text-3xl font-bold text-white">{artist?.name || user?.name}</h2>
                {artist?.is_verified && <VerifiedBadge size="lg" />}
              </div>
              <p className="text-zinc-400 mb-2">{formatNumber(artist?.monthly_listeners || 0)} auditeurs mensuels</p>
              {artist?.genres && (
                <div className="flex gap-2 flex-wrap">
                  {(Array.isArray(artist.genres) ? artist.genres : []).map((genre: string) => (
                    <Badge key={genre} className="bg-zinc-700/50 text-zinc-300 border-0">
                      {genre.trim()}
                    </Badge>
                  ))}
                </div>
              )}
            </div>
            <div className="flex gap-2">
              <Button variant="outline" size="icon" className="border-zinc-700 bg-transparent">
                <Share2 className="w-4 h-4" />
              </Button>
            </div>
          </div>

          <p className="text-zinc-400 mt-4 max-w-2xl">
            {artist?.bio || "Aucune bio pour le moment. Ajoutez une bio dans les parametres."}
          </p>

          {/* Social Links */}
          <div className="flex gap-3 mt-4">
            {socialLinks.instagram && (
              <a
                href={`https://instagram.com/${socialLinks.instagram.replace("@", "")}`}
                target="_blank"
                rel="noopener noreferrer"
                className="w-10 h-10 bg-zinc-700/50 rounded-full flex items-center justify-center text-zinc-400 hover:text-white hover:bg-zinc-700 transition-colors"
              >
                <Instagram className="w-5 h-5" />
              </a>
            )}
            {socialLinks.twitter && (
              <a
                href={`https://twitter.com/${socialLinks.twitter.replace("@", "")}`}
                target="_blank"
                rel="noopener noreferrer"
                className="w-10 h-10 bg-zinc-700/50 rounded-full flex items-center justify-center text-zinc-400 hover:text-white hover:bg-zinc-700 transition-colors"
              >
                <Twitter className="w-5 h-5" />
              </a>
            )}
            {socialLinks.youtube && (
              <a
                href={`https://youtube.com/${socialLinks.youtube.replace("@", "")}`}
                target="_blank"
                rel="noopener noreferrer"
                className="w-10 h-10 bg-zinc-700/50 rounded-full flex items-center justify-center text-zinc-400 hover:text-white hover:bg-zinc-700 transition-colors"
              >
                <Youtube className="w-5 h-5" />
              </a>
            )}
            {socialLinks.website && (
              <a
                href={socialLinks.website.startsWith("http") ? socialLinks.website : `https://${socialLinks.website}`}
                target="_blank"
                rel="noopener noreferrer"
                className="w-10 h-10 bg-zinc-700/50 rounded-full flex items-center justify-center text-zinc-400 hover:text-white hover:bg-zinc-700 transition-colors"
              >
                <Globe className="w-5 h-5" />
              </a>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Stats */}
      <div className="grid sm:grid-cols-3 gap-4">
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardContent className="p-4 flex items-center gap-4">
            <div className="w-12 h-12 bg-purple-500/20 rounded-lg flex items-center justify-center">
              <Users className="w-6 h-6 text-purple-400" />
            </div>
            <div>
              <p className="text-zinc-400 text-sm">Followers</p>
              <p className="text-white text-xl font-bold">
                {formatNumber(artist?.total_followers || artist?.follower_count || 0)}
              </p>
            </div>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardContent className="p-4 flex items-center gap-4">
            <div className="w-12 h-12 bg-purple-500/20 rounded-lg flex items-center justify-center">
              <Play className="w-6 h-6 text-purple-400" />
            </div>
            <div>
              <p className="text-zinc-400 text-sm">Ecoutes totales</p>
              <p className="text-white text-xl font-bold">{formatNumber(artist?.total_streams || 0)}</p>
            </div>
          </CardContent>
        </Card>
        <Card className="bg-zinc-800/30 border-zinc-700/50">
          <CardContent className="p-4 flex items-center gap-4">
            <div className="w-12 h-12 bg-purple-500/20 rounded-lg flex items-center justify-center">
              <Music className="w-6 h-6 text-purple-400" />
            </div>
            <div>
              <p className="text-zinc-400 text-sm">Titres publies</p>
              <p className="text-white text-xl font-bold">{artist?.track_count || tracks.length || 0}</p>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Top Tracks */}
      <Card className="bg-zinc-800/30 border-zinc-700/50">
        <CardHeader>
          <CardTitle className="text-white">Mes titres</CardTitle>
        </CardHeader>
        <CardContent>
          {loadingTracks ? (
            <div className="flex items-center justify-center py-8">
              <Loader2 className="w-6 h-6 animate-spin text-purple-500" />
            </div>
          ) : tracks.length === 0 ? (
            <div className="text-center py-8">
              <Music className="w-12 h-12 text-zinc-600 mx-auto mb-4" />
              <p className="text-zinc-400 mb-4">Aucun titre pour le moment</p>
              <Link href="/artist/upload">
                <Button className="bg-purple-600 hover:bg-purple-700">Uploader votre premier titre</Button>
              </Link>
            </div>
          ) : (
            <div className="space-y-2">
              {tracks.slice(0, 5).map((track: any, index: number) => (
                <div
                  key={track.id}
                  onClick={() => handlePlayTrack(track)}
                  className="flex items-center gap-4 p-3 rounded-lg hover:bg-zinc-700/30 transition-colors cursor-pointer group"
                >
                  <span className="text-zinc-500 w-6 text-center font-medium">{index + 1}</span>
                  <div className="relative">
                    <img
                      src={track.cover_url || "/placeholder.svg?height=48&width=48&query=music"}
                      alt={track.title}
                      className="w-12 h-12 bg-zinc-700 rounded object-cover"
                    />
                    <div className="absolute inset-0 bg-black/50 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity rounded">
                      <Play className="w-5 h-5 text-white" fill="white" />
                    </div>
                  </div>
                  <div className="flex-1">
                    <p className="text-white font-medium">{track.title}</p>
                    <p className="text-zinc-400 text-sm">{formatNumber(track.total_streams || 0)} streams</p>
                  </div>
                  <span className="text-zinc-400 text-sm">{formatDuration(track.duration_ms || 0)}</span>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
