'use client'

import { useState } from 'react'
import type { TrainingMedia } from '@/lib/sdk/training/types'
import { generateVideo, publishMedia } from '@/lib/sdk/training/api'

interface VideoPlayerProps {
  moduleId: string
  video: TrainingMedia | null
  onMediaUpdate: () => void
}

export default function VideoPlayer({ moduleId, video, onMediaUpdate }: VideoPlayerProps) {
  const [generating, setGenerating] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleGenerate() {
    setGenerating(true)
    setError(null)
    try {
      await generateVideo(moduleId)
      onMediaUpdate()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Video-Generierung fehlgeschlagen')
    } finally {
      setGenerating(false)
    }
  }

  async function handlePublishToggle() {
    if (!video) return
    try {
      await publishMedia(video.id, !video.is_published)
      onMediaUpdate()
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Fehler beim Aendern des Status')
    }
  }

  function formatDuration(seconds: number): string {
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins}:${secs.toString().padStart(2, '0')}`
  }

  function formatSize(bytes: number): string {
    if (bytes < 1024) return `${bytes} B`
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
  }

  return (
    <div className="border rounded-lg p-4 bg-white">
      <div className="flex items-center justify-between mb-3">
        <h4 className="text-sm font-medium text-gray-700">Praesentationsvideo</h4>
        {!video && (
          <button
            onClick={handleGenerate}
            disabled={generating}
            className="px-3 py-1.5 text-xs bg-purple-600 text-white rounded hover:bg-purple-700 disabled:opacity-50"
          >
            {generating ? 'Generiere Video...' : 'Video generieren'}
          </button>
        )}
      </div>

      {error && (
        <div className="text-xs text-red-600 mb-2">{error}</div>
      )}

      {generating && !video && (
        <div className="flex items-center gap-2 text-sm text-gray-500">
          <div className="animate-spin h-4 w-4 border-2 border-purple-500 border-t-transparent rounded-full" />
          Video wird generiert (Folien + Audio, kann einige Minuten dauern)...
        </div>
      )}

      {video && video.status === 'processing' && (
        <div className="flex items-center gap-2 text-sm text-gray-500">
          <div className="animate-spin h-4 w-4 border-2 border-purple-500 border-t-transparent rounded-full" />
          Video wird verarbeitet...
        </div>
      )}

      {video && video.status === 'failed' && (
        <div className="space-y-2">
          <div className="text-xs text-red-600">Generierung fehlgeschlagen: {video.error_message}</div>
          <button
            onClick={handleGenerate}
            disabled={generating}
            className="px-3 py-1.5 text-xs bg-purple-600 text-white rounded hover:bg-purple-700 disabled:opacity-50"
          >
            Erneut versuchen
          </button>
        </div>
      )}

      {video && video.status === 'completed' && (
        <div className="space-y-3">
          <video controls className="w-full rounded-lg bg-black" preload="none">
            <source src={`/api/sdk/v1/training/media/${video.id}/stream`} type="video/mp4" />
            Ihr Browser unterstuetzt kein Video.
          </video>
          <div className="flex items-center justify-between text-xs text-gray-500">
            <div className="flex gap-4">
              <span>Dauer: {formatDuration(video.duration_seconds)}</span>
              <span>Groesse: {formatSize(video.file_size_bytes)}</span>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={handlePublishToggle}
                className={`px-2 py-1 rounded text-xs ${video.is_published ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-600'}`}
              >
                {video.is_published ? 'Veroeffentlicht' : 'Veroeffentlichen'}
              </button>
              <button
                onClick={handleGenerate}
                disabled={generating}
                className="px-2 py-1 text-xs bg-gray-100 text-gray-600 rounded hover:bg-gray-200 disabled:opacity-50"
              >
                Neu generieren
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
