"use client"

import { useState, useEffect } from "react"
import { useRouter, useParams } from "next/navigation"
import Link from "next/link"
import { Loader2, Play, CheckCircle, AlertCircle, ArrowLeft, Video } from "lucide-react"
import { supabase } from "@/lib/supabase"
import { getWorkoutVideoStatus } from "@/lib/ai"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { toast } from "sonner"

type Workout = {
  id: string
  title: string
  trainer_id: string
  exercises: { name: string; duration: number }[]
  video_url: string | null
}

type Trainer = {
  id: string
  name: string
  avatar_url: string | null
  specialty: string
}

export default function GenerateVideoPage() {
  const router = useRouter()
  const params = useParams()
  const workoutId = params.id as string

  const [workout, setWorkout] = useState<Workout | null>(null)
  const [trainer, setTrainer] = useState<Trainer | null>(null)
  const [loading, setLoading] = useState(true)
  const [generating, setGenerating] = useState(false)
  const [progress, setProgress] = useState(0)
  const [status, setStatus] = useState<"idle" | "generating" | "done" | "error">("idle")
  const [videoStatus, setVideoStatus] = useState<{
    hasVideo: boolean
    videoUrl: string | null
    inProgram: boolean
    videoGenerated: boolean
  } | null>(null)

  useEffect(() => {
    if (workoutId) {
      loadData(workoutId)
    }
  }, [workoutId])

  const loadData = async (id: string) => {
    setLoading(true)

    const { data: w } = await (supabase.from("workouts") as any)
      .select("*")
      .eq("id", id)
      .single()

    if (!w) {
      toast.error("Workout not found")
      router.push("/workouts")
      return
    }
    setWorkout(w)

    if (w.trainer_id) {
      const { data: t } = await (supabase.from("trainers") as any)
        .select("*")
        .eq("id", w.trainer_id)
        .single()
      setTrainer(t)
    }

    const videoStatus = await getWorkoutVideoStatus(id)
    setVideoStatus(videoStatus)

    setLoading(false)
  }

  const handleGenerate = async () => {
    if (!workout || !trainer) return

    setStatus("generating")
    setGenerating(true)
    setProgress(0)

    try {
      const progressInterval = setInterval(() => {
        setProgress(p => Math.min(p + 5, 90))
      }, 3000)

      const response = await fetch('/api/ai/generate-video', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          workoutId: workout.id,
          trainerId: trainer.id,
          trainerAvatarUrl: trainer.avatar_url,
          exercises: workout.exercises,
        }),
      })

      clearInterval(progressInterval)

      if (!response.ok) {
        const error = await response.json()
        throw new Error(error.error || 'Generation failed')
      }

      const { videos, videoCount } = await response.json()

      setProgress(100)
      setVideoStatus(prev => prev ? { ...prev, hasVideo: true, videoUrl: videos[0]?.videoUrl } : null)

      if (videoStatus?.inProgram) {
        await (supabase.from("program_workouts") as any)
          .update({ video_generated: true })
          .eq("workout_id", workout.id)
      }

      setStatus("done")
      toast.success(`Generated ${videoCount} exercise video(s)!`)
    } catch (err) {
      console.error("Generation failed:", err)
      toast.error(err instanceof Error ? err.message : "Failed to generate video")
      setStatus("error")
    } finally {
      setGenerating(false)
    }
  }

  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-[400px]">
        <Loader2 className="w-8 h-8 animate-spin text-orange-500" />
      </div>
    )
  }

  if (!workout) {
    return (
      <div className="p-8 text-center">
        <p className="text-neutral-400">Workout not found</p>
      </div>
    )
  }

  const needsGeneration = !videoStatus?.hasVideo

  return (
    <div className="p-8 max-w-3xl">
      <Button variant="ghost" asChild className="mb-4 text-neutral-400 hover:text-white">
        <Link href={`/workouts/${workout.id}`}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back to Workout
        </Link>
      </Button>

      <h1 className="text-2xl font-bold text-white mb-6">Generate Workout Video</h1>

      <Card className="bg-neutral-900 border-neutral-800">
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="text-white">{workout.title}</CardTitle>
            {videoStatus?.inProgram && (
              <Badge variant="outline" className="border-amber-500 text-amber-500">
                In Program
              </Badge>
            )}
          </div>
        </CardHeader>
        <CardContent className="space-y-6">
          <div className="flex items-center gap-4 p-4 rounded-lg bg-neutral-800">
            {trainer?.avatar_url && (
              <img
                src={trainer.avatar_url}
                alt={trainer.name}
                className="w-16 h-16 rounded-full object-cover border-2 border-neutral-700"
              />
            )}
            <div>
              <p className="font-medium text-white">{trainer?.name}</p>
              <p className="text-sm text-neutral-400">{trainer?.specialty}</p>
            </div>
          </div>

          {videoStatus?.inProgram && (
            <div className="flex items-start gap-2 p-3 rounded-lg bg-amber-500/10 border border-amber-500/20">
              <AlertCircle className="w-5 h-5 text-amber-500 shrink-0 mt-0.5" />
              <div className="text-sm">
                <p className="text-amber-500 font-medium">Workout is in a program</p>
                <p className="text-neutral-400">
                  The video_generated flag will be set to true after generation.
                </p>
              </div>
            </div>
          )}

          <div>
            <h3 className="font-medium text-white mb-3">Exercises</h3>
            <div className="space-y-2">
              {workout.exercises?.map((ex, i) => (
                <div key={i} className="flex items-center gap-3 text-sm">
                  <span className="w-8 h-8 rounded-full bg-neutral-800 flex items-center justify-center text-neutral-400 text-xs">
                    {i + 1}
                  </span>
                  <span className="text-neutral-300">{ex.name}</span>
                  <span className="text-neutral-500 ml-auto">{ex.duration}s</span>
                </div>
              ))}
            </div>
          </div>

          {videoStatus?.hasVideo && videoStatus.videoUrl && !generating && (
            <div>
              <h3 className="font-medium text-white mb-3">Generated Video</h3>
              <video
                src={videoStatus.videoUrl}
                controls
                autoPlay
                loop
                className="w-full max-h-80 rounded-lg border border-neutral-700"
              />
              <p className="text-xs text-neutral-500 mt-2">
                Video loops seamlessly (8 seconds)
              </p>
            </div>
          )}

          {needsGeneration && (
            <div className="pt-4 border-t border-neutral-800">
              {status === "generating" ? (
                <div className="space-y-4">
                  <div className="flex items-center gap-3">
                    <Loader2 className="w-5 h-5 animate-spin text-purple-500" />
                    <span className="text-white">Generating video with Veo 3.1...</span>
                  </div>
                  <div className="h-2 w-full rounded-full bg-neutral-800">
                    <div
                      className="h-full bg-purple-500 transition-all duration-1000"
                      style={{ width: `${progress}%` }}
                    />
                  </div>
                  <div className="flex items-center gap-2 text-sm text-neutral-400">
                    <Video className="w-4 h-4" />
                    <span>Creating 8-second looping video with {trainer?.name}</span>
                  </div>
                  <p className="text-xs text-neutral-500">
                    This may take up to 2 minutes. Please wait...
                  </p>
                </div>
              ) : (
                <Button
                  onClick={handleGenerate}
                  className="w-full bg-purple-500 hover:bg-purple-600"
                >
                  <Play className="w-4 h-4" />
                  Generate 8s Looping Video
                </Button>
              )}
            </div>
          )}

          {status === "done" && (
            <div className="flex items-center gap-2 p-3 rounded-lg bg-green-500/10 border border-green-500/20">
              <CheckCircle className="w-5 h-5 text-green-500" />
              <span className="text-green-500 font-medium">Video generated and saved!</span>
            </div>
          )}

          {status === "error" && (
            <div className="flex items-center gap-2 p-3 rounded-lg bg-red-500/10 border border-red-500/20">
              <AlertCircle className="w-5 h-5 text-red-500" />
              <span className="text-red-500">Video generation failed. Check console for details.</span>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
