"use client"

import type React from "react"
import { useState, useRef } from "react"
import useSWR from "swr"
import Image from "next/image"
import {
  Search,
  MoreVertical,
  Play,
  Edit,
  Trash2,
  Eye,
  Upload,
  ChevronLeft,
  ChevronRight,
  Check,
  Loader2,
  X,
  Plus,
  Video,
  DollarSign,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, DropdownMenuSeparator } from "@/components/ui/dropdown-menu"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { ConfirmDialog } from "@/components/confirm-dialog"
import { useToast } from "@/hooks/use-toast"
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"

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
  like_count: number
  status: string
  is_free: boolean
  price_fcfa: number
  created_at: string
}

export default function AdminVideosPage() {
  const { data: videosData, isLoading, mutate } = useSWR("/api/videos?include_all=true&limit=100", fetcher)
  const { data: artistsData } = useSWR("/api/artists?limit=100", fetcher)
  const { toast } = useToast()

  const videos: VideoItem[] = videosData?.videos || []
  const artists = artistsData?.artists || []

  const [searchQuery, setSearchQuery] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [showAddVideo, setShowAddVideo] = useState(false)
  const [showEditVideo, setShowEditVideo] = useState<VideoItem | null>(null)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState<string | null>(null)
  const [currentPage, setCurrentPage] = useState(1)
  const videosPerPage = 10
  const [isUploading, setIsUploading] = useState(false)
  const [videoFile, setVideoFile] = useState<File | null>(null)
  const [thumbnailFile, setThumbnailFile] = useState<File | null>(null)
  const videoInputRef = useRef<HTMLInputElement>(null)
  const thumbnailInputRef = useRef<HTMLInputElement>(null)

  const [formData, setFormData] = useState({
    title: "",
    description: "",
    artist_id: "",
    is_free: true,
    price_fcfa: 0,
    status: "pending" as "published" | "draft" | "pending" | "rejected",
  })

  const showToast = (message: string, type = "success") => {
    toast({ message, type })
  }

  const resetForm = () => {
    setFormData({
      title: "",
      description: "",
      artist_id: "",
      is_free: true,
      price_fcfa: 0,
      status: "pending",
    })
    setVideoFile(null)
    setThumbnailFile(null)
  }

  const filteredVideos = videos.filter((video) => {
    const matchesSearch =
      video.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (video.artist_name || "").toLowerCase().includes(searchQuery.toLowerCase())
    const matchesStatus = statusFilter === "all" || video.status === statusFilter
    return matchesSearch && matchesStatus
  })

  const paginatedVideos = filteredVideos.slice((currentPage - 1) * videosPerPage, currentPage * videosPerPage)
  const totalPages = Math.ceil(filteredVideos.length / videosPerPage)

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "published":
        return <Badge className="bg-green-500/20 text-green-400 border-0">Publié</Badge>
      case "draft":
        return <Badge className="bg-zinc-500/20 text-zinc-400 border-0">Brouillon</Badge>
      case "pending":
        return <Badge className="bg-yellow-500/20 text-yellow-400 border-0">En attente</Badge>
      case "rejected":
        return <Badge className="bg-red-500/20 text-red-400 border-0">Rejeté</Badge>
      default:
        return <Badge>{status}</Badge>
    }
  }

  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 handleVideoFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      setVideoFile(file)
    }
  }

  const handleThumbnailFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      setThumbnailFile(file)
    }
  }

  const uploadFile = async (file: File, type: "video" | "image") => {
    const formData = new FormData()
    formData.append("file", file)
    
    const endpoint = type === "video" ? "/api/upload/audio/direct" : "/api/upload/image"
    const res = await fetch(endpoint, {
      method: "POST",
      body: formData,
    })
    
    if (!res.ok) throw new Error(`Failed to upload ${type}`)
    const data = await res.json()
    return data.url
  }

  const handleAddVideo = async () => {
    if (!videoFile) {
      showToast("Veuillez sélectionner un fichier vidéo", "error")
      return
    }

    if (!formData.title) {
      showToast("Veuillez entrer un titre", "error")
      return
    }

    setIsUploading(true)
    try {
      // Upload video file
      const videoUrl = await uploadFile(videoFile, "video")
      
      // Upload thumbnail if provided
      let thumbnailUrl = null
      if (thumbnailFile) {
        thumbnailUrl = await uploadFile(thumbnailFile, "image")
      }

      // Create video record
      const res = await fetch("/api/videos", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: formData.title,
          description: formData.description || null,
          artist_id: formData.artist_id || null,
          video_url: videoUrl,
          thumbnail_url: thumbnailUrl,
          is_free: formData.is_free,
          price_fcfa: formData.is_free ? 0 : formData.price_fcfa,
        }),
      })

      if (res.ok) {
        mutate()
        showToast("Vidéo ajoutée avec succès")
        setShowAddVideo(false)
        resetForm()
      } else {
        throw new Error("Échec de la création de la vidéo")
      }
    } catch (error) {
      console.error("Add video error:", error)
      showToast("Erreur lors de l'ajout de la vidéo", "error")
    } finally {
      setIsUploading(false)
    }
  }

  const handleUpdateStatus = async (videoId: string, newStatus: string) => {
    try {
      const res = await fetch(`/api/videos/${videoId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: newStatus }),
      })

      if (res.ok) {
        mutate()
        showToast(`Vidéo ${newStatus === "published" ? "publiée" : "mise à jour"} avec succès`)
      } else {
        throw new Error("Failed to update video")
      }
    } catch (error) {
      console.error("Update status error:", error)
      showToast("Erreur lors de la mise à jour", "error")
    }
  }

  const handleDeleteVideo = async (videoId: string) => {
    try {
      const res = await fetch(`/api/videos/${videoId}`, {
        method: "DELETE",
      })

      if (res.ok) {
        mutate()
        showToast("Vidéo supprimée avec succès")
        setShowDeleteConfirm(null)
      } else {
        throw new Error("Failed to delete video")
      }
    } catch (error) {
      console.error("Delete video error:", error)
      showToast("Erreur lors de la suppression", "error")
    }
  }

  const handleEditVideo = async () => {
    if (!showEditVideo) return

    try {
      const res = await fetch(`/api/videos/${showEditVideo.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          title: formData.title,
          description: formData.description,
          is_free: formData.is_free,
          price_fcfa: formData.is_free ? 0 : formData.price_fcfa,
        }),
      })

      if (res.ok) {
        mutate()
        showToast("Vidéo mise à jour avec succès")
        setShowEditVideo(null)
        resetForm()
      } else {
        throw new Error("Failed to update video")
      }
    } catch (error) {
      console.error("Edit video error:", error)
      showToast("Erreur lors de la mise à jour", "error")
    }
  }

  const openEditDialog = (video: VideoItem) => {
    setFormData({
      title: video.title,
      description: video.description || "",
      artist_id: video.artist_id || "",
      is_free: video.is_free,
      price_fcfa: video.price_fcfa,
      status: video.status as any,
    })
    setShowEditVideo(video)
  }

  return (
    <div className="flex-1 space-y-6 p-6">
      {/* Header */}
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Gestion des Vidéos</h1>
          <p className="text-muted-foreground">Gérez les vidéos de la plateforme</p>
        </div>
        <Button onClick={() => setShowAddVideo(true)} className="gap-2">
          <Plus className="h-4 w-4" />
          Ajouter une vidéo
        </Button>
      </div>

      {/* Filters */}
      <div className="flex flex-col gap-4 md:flex-row md:items-center">
        <div className="relative flex-1">
          <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>
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Statut" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Tous les statuts</SelectItem>
            <SelectItem value="published">Publié</SelectItem>
            <SelectItem value="pending">En attente</SelectItem>
            <SelectItem value="draft">Brouillon</SelectItem>
            <SelectItem value="rejected">Rejeté</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Videos Table */}
      <div className="rounded-lg border border-border bg-card">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-border bg-muted/50">
                <th className="px-4 py-3 text-left text-sm font-medium text-muted-foreground">Vidéo</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-muted-foreground">Artiste</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-muted-foreground">Durée</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-muted-foreground">Vues</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-muted-foreground">Prix</th>
                <th className="px-4 py-3 text-left text-sm font-medium text-muted-foreground">Statut</th>
                <th className="px-4 py-3 text-right text-sm font-medium text-muted-foreground">Actions</th>
              </tr>
            </thead>
            <tbody>
              {isLoading ? (
                <tr>
                  <td colSpan={7} className="px-4 py-8 text-center">
                    <Loader2 className="mx-auto h-6 w-6 animate-spin text-muted-foreground" />
                  </td>
                </tr>
              ) : paginatedVideos.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-4 py-8 text-center text-muted-foreground">
                    Aucune vidéo trouvée
                  </td>
                </tr>
              ) : (
                paginatedVideos.map((video) => (
                  <tr key={video.id} className="border-b border-border last:border-0 hover:bg-muted/30">
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-3">
                        <div className="relative h-12 w-20 flex-shrink-0 overflow-hidden rounded bg-muted">
                          {video.thumbnail_url ? (
                            <Image
                              src={video.thumbnail_url}
                              alt={video.title}
                              fill
                              className="object-cover"
                            />
                          ) : (
                            <div className="flex h-full w-full items-center justify-center">
                              <Video className="h-5 w-5 text-muted-foreground" />
                            </div>
                          )}
                        </div>
                        <div className="min-w-0">
                          <p className="truncate font-medium text-foreground">{video.title}</p>
                          {video.description && (
                            <p className="truncate text-xs text-muted-foreground">{video.description}</p>
                          )}
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-sm text-muted-foreground">
                      {video.artist_name || "—"}
                    </td>
                    <td className="px-4 py-3 text-sm text-muted-foreground">
                      {formatDuration(video.duration_ms)}
                    </td>
                    <td className="px-4 py-3 text-sm text-muted-foreground">
                      {formatViews(video.view_count)}
                    </td>
                    <td className="px-4 py-3 text-sm">
                      {video.is_free ? (
                        <Badge variant="secondary">Gratuit</Badge>
                      ) : (
                        <span className="font-medium text-primary">{video.price_fcfa} FCFA</span>
                      )}
                    </td>
                    <td className="px-4 py-3">{getStatusBadge(video.status)}</td>
                    <td className="px-4 py-3 text-right">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon" className="h-8 w-8">
                            <MoreVertical className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem onClick={() => window.open(video.video_url, "_blank")}>
                            <Play className="mr-2 h-4 w-4" />
                            Voir la vidéo
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => openEditDialog(video)}>
                            <Edit className="mr-2 h-4 w-4" />
                            Modifier
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          {video.status === "pending" && (
                            <>
                              <DropdownMenuItem onClick={() => handleUpdateStatus(video.id, "published")}>
                                <Check className="mr-2 h-4 w-4 text-green-500" />
                                Publier
                              </DropdownMenuItem>
                              <DropdownMenuItem onClick={() => handleUpdateStatus(video.id, "rejected")}>
                                <X className="mr-2 h-4 w-4 text-red-500" />
                                Rejeter
                              </DropdownMenuItem>
                              <DropdownMenuSeparator />
                            </>
                          )}
                          {video.status === "published" && (
                            <>
                              <DropdownMenuItem onClick={() => handleUpdateStatus(video.id, "archived")}>
                                <Eye className="mr-2 h-4 w-4" />
                                Archiver
                              </DropdownMenuItem>
                              <DropdownMenuSeparator />
                            </>
                          )}
                          <DropdownMenuItem
                            onClick={() => setShowDeleteConfirm(video.id)}
                            className="text-destructive"
                          >
                            <Trash2 className="mr-2 h-4 w-4" />
                            Supprimer
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between border-t border-border px-4 py-3">
            <p className="text-sm text-muted-foreground">
              {filteredVideos.length} vidéo{filteredVideos.length > 1 ? "s" : ""}
            </p>
            <div className="flex items-center gap-2">
              <Button
                variant="outline"
                size="icon"
                onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                disabled={currentPage === 1}
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <span className="text-sm">
                {currentPage} / {totalPages}
              </span>
              <Button
                variant="outline"
                size="icon"
                onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                disabled={currentPage === totalPages}
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>
        )}
      </div>

      {/* Add Video Dialog */}
      <Dialog open={showAddVideo} onOpenChange={setShowAddVideo}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>Ajouter une vidéo</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="title">Titre *</Label>
              <Input
                id="title"
                value={formData.title}
                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                placeholder="Titre de la vidéo"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="description">Description</Label>
              <Textarea
                id="description"
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="Description de la vidéo"
                rows={3}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="artist">Artiste</Label>
              <Select
                value={formData.artist_id}
                onValueChange={(value) => setFormData({ ...formData, artist_id: value })}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Sélectionner un artiste" />
                </SelectTrigger>
                <SelectContent>
                  {artists.map((artist: any) => (
                    <SelectItem key={artist.id} value={artist.id}>
                      {artist.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Fichier vidéo *</Label>
              <input
                ref={videoInputRef}
                type="file"
                accept="video/*"
                onChange={handleVideoFileChange}
                className="hidden"
              />
              <Button
                type="button"
                variant="outline"
                className="w-full gap-2"
                onClick={() => videoInputRef.current?.click()}
              >
                <Upload className="h-4 w-4" />
                {videoFile ? videoFile.name : "Sélectionner une vidéo"}
              </Button>
            </div>
            <div className="space-y-2">
              <Label>Miniature</Label>
              <input
                ref={thumbnailInputRef}
                type="file"
                accept="image/*"
                onChange={handleThumbnailFileChange}
                className="hidden"
              />
              <Button
                type="button"
                variant="outline"
                className="w-full gap-2"
                onClick={() => thumbnailInputRef.current?.click()}
              >
                <Upload className="h-4 w-4" />
                {thumbnailFile ? thumbnailFile.name : "Sélectionner une miniature"}
              </Button>
            </div>
            <div className="flex items-center justify-between">
              <Label htmlFor="is_free">Vidéo gratuite</Label>
              <Switch
                id="is_free"
                checked={formData.is_free}
                onCheckedChange={(checked) => setFormData({ ...formData, is_free: checked })}
              />
            </div>
            {!formData.is_free && (
              <div className="space-y-2">
                <Label htmlFor="price">Prix (FCFA)</Label>
                <Input
                  id="price"
                  type="number"
                  value={formData.price_fcfa}
                  onChange={(e) => setFormData({ ...formData, price_fcfa: Number(e.target.value) })}
                  placeholder="500"
                  min="0"
                />
              </div>
            )}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => { setShowAddVideo(false); resetForm(); }}>
              Annuler
            </Button>
            <Button onClick={handleAddVideo} disabled={isUploading}>
              {isUploading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Upload en cours...
                </>
              ) : (
                "Ajouter"
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Edit Video Dialog */}
      <Dialog open={!!showEditVideo} onOpenChange={() => { setShowEditVideo(null); resetForm(); }}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>Modifier la vidéo</DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="edit-title">Titre</Label>
              <Input
                id="edit-title"
                value={formData.title}
                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="edit-description">Description</Label>
              <Textarea
                id="edit-description"
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                rows={3}
              />
            </div>
            <div className="flex items-center justify-between">
              <Label htmlFor="edit-is_free">Vidéo gratuite</Label>
              <Switch
                id="edit-is_free"
                checked={formData.is_free}
                onCheckedChange={(checked) => setFormData({ ...formData, is_free: checked })}
              />
            </div>
            {!formData.is_free && (
              <div className="space-y-2">
                <Label htmlFor="edit-price">Prix (FCFA)</Label>
                <Input
                  id="edit-price"
                  type="number"
                  value={formData.price_fcfa}
                  onChange={(e) => setFormData({ ...formData, price_fcfa: Number(e.target.value) })}
                  min="0"
                />
              </div>
            )}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => { setShowEditVideo(null); resetForm(); }}>
              Annuler
            </Button>
            <Button onClick={handleEditVideo}>
              Enregistrer
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation */}
      <ConfirmDialog
        open={!!showDeleteConfirm}
        onOpenChange={() => setShowDeleteConfirm(null)}
        title="Supprimer la vidéo"
        description="Êtes-vous sûr de vouloir supprimer cette vidéo ? Cette action est irréversible."
        confirmText="Supprimer"
        onConfirm={() => showDeleteConfirm && handleDeleteVideo(showDeleteConfirm)}
        variant="destructive"
      />
    </div>
  )
}
