"use client"

import { useState, useEffect, use } from "react"
import useSWR from "swr"
import Image from "next/image"
import Link from "next/link"
import { useRouter } from "next/navigation"
import {
  Play,
  Video,
  Eye,
  Clock,
  Heart,
  Share2,
  Lock,
  Loader2,
  ArrowLeft,
  CheckCircle,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { useToast } from "@/hooks/use-toast"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog"

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

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

export default function VideoWatchPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params)
  const router = useRouter()
  const { toast } = useToast()
  
  const { data, isLoading, mutate } = useSWR(`/api/videos/${id}`, fetcher)
  const video: VideoData | null = data?.video || null

  const [isPlaying, setIsPlaying] = useState(false)
  const [hasPurchased, setHasPurchased] = useState(false)
  const [isPurchasing, setIsPurchasing] = useState(false)
  const [showPurchaseDialog, setShowPurchaseDialog] = useState(false)
  const [currentUserId, setCurrentUserId] = useState<string | null>(null)

  // Get current user
  useEffect(() => {
    const checkUser = async () => {
      try {
        const token = localStorage.getItem("auth_token")
        if (token) {
          const res = await fetch("/api/auth/me", {
            headers: { Authorization: `Bearer ${token}` },
          })
          if (res.ok) {
            const data = await res.json()
            setCurrentUserId(data.user?.id || null)
          }
        }
      } catch (error) {
        console.error("Failed to get user:", error)
      }
    }
    checkUser()
  }, [])

  // Check if user has purchased this video
  useEffect(() => {
    const checkPurchase = async () => {
      if (!currentUserId || !video || video.is_free) return
      
      try {
        const res = await fetch(`/api/videos/${id}/purchase?user_id=${currentUserId}`)
        if (res.ok) {
          const data = await res.json()
          setHasPurchased(data.purchased)
        }
      } catch (error) {
        console.error("Failed to check purchase:", error)
      }
    }
    checkPurchase()
  }, [currentUserId, video, id])

  // Record view when video plays
  const handlePlay = async () => {
    if (!video) return

    // Check if video is free or purchased
    if (!video.is_free && !hasPurchased) {
      setShowPurchaseDialog(true)
      return
    }

    setIsPlaying(true)

    // Record view
    try {
      await fetch(`/api/videos/${id}/view`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ user_id: currentUserId }),
      })
    } catch (error) {
      console.error("Failed to record view:", error)
    }
  }

  const handlePurchase = async () => {
    if (!currentUserId) {
      toast({ message: "Veuillez vous connecter pour acheter", type: "error" })
      router.push("/login")
      return
    }

    setIsPurchasing(true)
    try {
      const res = await fetch(`/api/videos/${id}/purchase`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ user_id: currentUserId }),
      })

      if (res.ok) {
        setHasPurchased(true)
        setShowPurchaseDialog(false)
        toast({ message: "Vidéo achetée avec succès!", type: "success" })
        // Auto-play after purchase
        setIsPlaying(true)
      } else {
        const data = await res.json()
        toast({ message: data.error || "Erreur lors de l'achat", type: "error" })
      }
    } catch (error) {
      console.error("Purchase error:", error)
      toast({ message: "Erreur lors de l'achat", type: "error" })
    } finally {
      setIsPurchasing(false)
    }
  }

  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 formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString("fr-FR", {
      day: "numeric",
      month: "long",
      year: "numeric",
    })
  }

  const handleShare = async () => {
    if (navigator.share) {
      try {
        await navigator.share({
          title: video?.title,
          url: window.location.href,
        })
      } catch (error) {
        // User cancelled
      }
    } else {
      navigator.clipboard.writeText(window.location.href)
      toast({ message: "Lien copié dans le presse-papier", type: "success" })
    }
  }

  if (isLoading) {
    return (
      <div className="flex min-h-[60vh] items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    )
  }

  if (!video) {
    return (
      <div className="flex min-h-[60vh] flex-col items-center justify-center gap-4">
        <Video className="h-12 w-12 text-muted-foreground" />
        <h2 className="text-xl font-medium">Vidéo non trouvée</h2>
        <Button variant="outline" onClick={() => router.back()}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Retour
        </Button>
      </div>
    )
  }

  const canWatch = video.is_free || hasPurchased

  return (
    <div className="flex-1 space-y-6 p-4 md:p-6">
      {/* Back button */}
      <Button variant="ghost" onClick={() => router.back()} className="gap-2">
        <ArrowLeft className="h-4 w-4" />
        Retour aux vidéos
      </Button>

      {/* Video Player */}
      <div className="relative aspect-video w-full overflow-hidden rounded-xl bg-black">
        {isPlaying && canWatch ? (
          <video
            src={video.video_url}
            controls
            autoPlay
            className="h-full w-full"
            poster={video.thumbnail_url || undefined}
          />
        ) : (
          <>
            {/* Thumbnail */}
            {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 bg-gradient-to-br from-primary/20 to-primary/5">
                <Video className="h-20 w-20 text-muted-foreground" />
              </div>
            )}

            {/* Overlay */}
            <div className="absolute inset-0 flex flex-col items-center justify-center bg-black/50">
              {!video.is_free && !hasPurchased ? (
                <>
                  <Lock className="mb-4 h-12 w-12 text-white" />
                  <p className="mb-4 text-lg font-medium text-white">Vidéo payante</p>
                  <Button size="lg" onClick={() => setShowPurchaseDialog(true)}>
                    Acheter pour {video.price_fcfa} FCFA
                  </Button>
                </>
              ) : (
                <Button
                  size="lg"
                  className="gap-2 rounded-full px-8"
                  onClick={handlePlay}
                >
                  <Play className="h-6 w-6 fill-current" />
                  Regarder
                </Button>
              )}
            </div>
          </>
        )}
      </div>

      {/* Video Info */}
      <div className="space-y-4">
        <div className="flex flex-wrap items-start justify-between gap-4">
          <div className="space-y-2">
            <h1 className="text-2xl font-bold text-foreground md:text-3xl">{video.title}</h1>
            <div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
              <span className="flex items-center gap-1">
                <Eye className="h-4 w-4" />
                {formatViews(video.view_count)} vues
              </span>
              <span className="flex items-center gap-1">
                <Clock className="h-4 w-4" />
                {formatDate(video.created_at)}
              </span>
              {!video.is_free && (
                <Badge variant={hasPurchased ? "secondary" : "default"}>
                  {hasPurchased ? (
                    <>
                      <CheckCircle className="mr-1 h-3 w-3" />
                      Acheté
                    </>
                  ) : (
                    `${video.price_fcfa} FCFA`
                  )}
                </Badge>
              )}
            </div>
          </div>

          {/* Actions */}
          <div className="flex items-center gap-2">
            <Button variant="outline" size="icon">
              <Heart className="h-5 w-5" />
            </Button>
            <Button variant="outline" size="icon" onClick={handleShare}>
              <Share2 className="h-5 w-5" />
            </Button>
          </div>
        </div>

        {/* Artist */}
        {video.artist_name && (
          <Link
            href={`/artist/${video.artist_id}`}
            className="flex items-center gap-3 rounded-lg p-3 transition-colors hover:bg-muted"
          >
            <div className="relative h-12 w-12 overflow-hidden rounded-full bg-muted">
              {video.artist_avatar ? (
                <Image
                  src={video.artist_avatar}
                  alt={video.artist_name}
                  fill
                  className="object-cover"
                />
              ) : (
                <div className="flex h-full w-full items-center justify-center text-lg font-medium">
                  {video.artist_name[0]}
                </div>
              )}
            </div>
            <div>
              <p className="font-medium text-foreground">{video.artist_name}</p>
              <p className="text-sm text-muted-foreground">Artiste</p>
            </div>
          </Link>
        )}

        {/* Description */}
        {video.description && (
          <div className="rounded-lg bg-muted/50 p-4">
            <p className="whitespace-pre-wrap text-sm text-foreground">{video.description}</p>
          </div>
        )}
      </div>

      {/* Purchase Dialog */}
      <Dialog open={showPurchaseDialog} onOpenChange={setShowPurchaseDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Acheter cette vidéo</DialogTitle>
            <DialogDescription>
              Achetez cette vidéo pour la regarder en illimité.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="flex items-center gap-4">
              <div className="relative h-20 w-32 overflow-hidden rounded-lg 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-8 w-8 text-muted-foreground" />
                  </div>
                )}
              </div>
              <div>
                <p className="font-medium">{video.title}</p>
                {video.artist_name && (
                  <p className="text-sm text-muted-foreground">{video.artist_name}</p>
                )}
              </div>
            </div>
            <div className="rounded-lg bg-muted p-4 text-center">
              <p className="text-2xl font-bold text-primary">{video.price_fcfa} FCFA</p>
              <p className="text-sm text-muted-foreground">Paiement unique</p>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowPurchaseDialog(false)}>
              Annuler
            </Button>
            <Button onClick={handlePurchase} disabled={isPurchasing}>
              {isPurchasing ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Traitement...
                </>
              ) : (
                "Confirmer l'achat"
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
