"use client"

import { useState } from "react"
import useSWR from "swr"
import Image from "next/image"
import Link from "next/link"
import { Search, Play, Video, Eye, Clock, Loader2 } from "lucide-react"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"

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

interface VideoItem {
  id: string
  title: string
  description: string | null
  artist_id: string | null
  artist_name?: string
  video_url: string
  thumbnail_url: string | null
  duration_ms: number | null
  view_count: number
  is_free: boolean
  price_fcfa: number
  created_at: string
}

export default function VideosPage() {
  const [searchQuery, setSearchQuery] = useState("")
  const { data, isLoading } = useSWR(
    `/api/videos?limit=50${searchQuery ? `&search=${encodeURIComponent(searchQuery)}` : ""}`,
    fetcher
  )

  const videos: VideoItem[] = data?.videos || []

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

  const formatDuration = (ms: number | null) => {
    if (!ms) return "0:00"
    const totalSeconds = Math.floor(ms / 1000)
    const minutes = Math.floor(totalSeconds / 60)
    const secs = totalSeconds % 60
    return `${minutes}:${secs.toString().padStart(2, "0")}`
  }

  const formatDate = (dateString: string) => {
    const date = new Date(dateString)
    const now = new Date()
    const diffDays = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24))
    
    if (diffDays === 0) return "Aujourd'hui"
    if (diffDays === 1) return "Hier"
    if (diffDays < 7) return `Il y a ${diffDays} jours`
    if (diffDays < 30) return `Il y a ${Math.floor(diffDays / 7)} semaines`
    if (diffDays < 365) return `Il y a ${Math.floor(diffDays / 30)} mois`
    return `Il y a ${Math.floor(diffDays / 365)} ans`
  }

  return (
    <div className="flex-1 space-y-6 p-4 md:p-6">
      {/* Header */}
      <div className="space-y-4">
        <div>
          <h1 className="text-2xl font-bold text-foreground md:text-3xl">Vidéos</h1>
          <p className="text-muted-foreground">Découvrez les clips et vidéos de vos artistes préférés</p>
        </div>

        {/* Search */}
        <div className="relative max-w-md">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Rechercher une vidéo..."
            className="pl-10"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
          />
        </div>
      </div>

      {/* Videos Grid */}
      {isLoading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
        </div>
      ) : videos.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-12 text-center">
          <Video className="mb-4 h-12 w-12 text-muted-foreground" />
          <h3 className="text-lg font-medium">Aucune vidéo trouvée</h3>
          <p className="text-muted-foreground">
            {searchQuery ? "Essayez une autre recherche" : "Les vidéos apparaîtront ici"}
          </p>
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {videos.map((video) => (
            <Link
              key={video.id}
              href={`/videos/${video.id}`}
              className="group overflow-hidden rounded-xl border border-border bg-card transition-all hover:border-primary/50 hover:shadow-lg"
            >
              {/* Thumbnail */}
              <div className="relative aspect-video overflow-hidden bg-muted">
                {video.thumbnail_url ? (
                  <Image
                    src={video.thumbnail_url}
                    alt={video.title}
                    fill
                    className="object-cover transition-transform group-hover:scale-105"
                  />
                ) : (
                  <div className="flex h-full w-full items-center justify-center bg-gradient-to-br from-primary/20 to-primary/5">
                    <Video className="h-10 w-10 text-muted-foreground" />
                  </div>
                )}
                
                {/* Play overlay */}
                <div className="absolute inset-0 flex items-center justify-center bg-black/0 transition-colors group-hover:bg-black/30">
                  <div className="scale-0 rounded-full bg-primary p-3 transition-transform group-hover:scale-100">
                    <Play className="h-6 w-6 fill-primary-foreground text-primary-foreground" />
                  </div>
                </div>

                {/* Duration badge */}
                {video.duration_ms && (
                  <div className="absolute bottom-2 right-2 rounded bg-black/70 px-1.5 py-0.5 text-xs font-medium text-white">
                    {formatDuration(video.duration_ms)}
                  </div>
                )}

                {/* Price badge */}
                {!video.is_free && (
                  <Badge className="absolute left-2 top-2 bg-primary text-primary-foreground">
                    {video.price_fcfa} FCFA
                  </Badge>
                )}
              </div>

              {/* Info */}
              <div className="p-3">
                <h3 className="line-clamp-2 font-medium text-foreground group-hover:text-primary">
                  {video.title}
                </h3>
                {video.artist_name && (
                  <p className="mt-1 text-sm text-muted-foreground">{video.artist_name}</p>
                )}
                <div className="mt-2 flex items-center gap-3 text-xs text-muted-foreground">
                  <span className="flex items-center gap-1">
                    <Eye className="h-3 w-3" />
                    {formatViews(video.view_count)} vues
                  </span>
                  <span className="flex items-center gap-1">
                    <Clock className="h-3 w-3" />
                    {formatDate(video.created_at)}
                  </span>
                </div>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  )
}
