import { useEffect, useRef, useState, useCallback } from 'react'
import Hls from 'hls.js'
import { 
  Play, 
  Pause, 
  Volume2, 
  VolumeX, 
  Maximize, 
  Minimize,
  RefreshCw,
  X,
  Tv2,
  AlertCircle,
  Bug
} from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'

interface VideoPlayerProps {
  url: string
  title?: string
  onClose?: () => void
  autoPlay?: boolean
}

interface DebugInfo {
  hlsSupported: boolean
  nativeHlsSupported: boolean
  url: string
  videoState: string
  hlsState: string
  error: string | null
  bufferLength: number
}

export default function VideoPlayer({ 
  url, 
  title = 'Canlı Yayın',
  onClose,
  autoPlay = true
}: VideoPlayerProps) {
  const videoRef = useRef<HTMLVideoElement>(null)
  const hlsRef = useRef<Hls | null>(null)
  const containerRef = useRef<HTMLDivElement>(null)
  
  const [isPlaying, setIsPlaying] = useState(false)
  const [isMuted, setIsMuted] = useState(false)
  const [isFullscreen, setIsFullscreen] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [showControls, setShowControls] = useState(true)
  const [volume, setVolume] = useState(1)
  const [showDebug, setShowDebug] = useState(false)
  const [debugInfo, setDebugInfo] = useState<DebugInfo>({
    hlsSupported: Hls.isSupported(),
    nativeHlsSupported: false,
    url: url,
    videoState: 'init',
    hlsState: 'none',
    error: null,
    bufferLength: 0
  })

  const updateDebug = useCallback((updates: Partial<DebugInfo>) => {
    setDebugInfo(prev => ({ ...prev, ...updates }))
  }, [])

  useEffect(() => {
    const video = videoRef.current
    if (!video) return

    setIsLoading(true)
    setError(null)
    updateDebug({ url, videoState: 'loading', error: null })

    // Check native HLS support
    const nativeHls = video.canPlayType('application/vnd.apple.mpegurl') !== ''
    updateDebug({ nativeHlsSupported: nativeHls })

    // Determine stream type
    const isHlsStream = url.includes('.m3u8')
    const isTsStream = url.includes('.ts')
    const isLiveStream = url.includes('/live/')

    console.log('[VideoPlayer] Stream info:', { url, isHlsStream, isTsStream, isLiveStream, hlsSupported: Hls.isSupported(), nativeHls })

    // Cleanup previous HLS instance
    if (hlsRef.current) {
      hlsRef.current.destroy()
      hlsRef.current = null
    }

    if ((isHlsStream || isLiveStream) && Hls.isSupported()) {
      // Use HLS.js for m3u8/live streams
      updateDebug({ hlsState: 'initializing' })
      
      const hls = new Hls({
        enableWorker: true,
        lowLatencyMode: true,
        backBufferLength: 90,
        maxBufferLength: 30,
        maxMaxBufferLength: 60,
        startLevel: -1, // Auto quality
        debug: false,
        xhrSetup: (xhr, urlToLoad) => {
          // Add headers if needed
          xhr.withCredentials = false
        }
      })

      hlsRef.current = hls

      hls.on(Hls.Events.MEDIA_ATTACHED, () => {
        console.log('[HLS] Media attached')
        updateDebug({ hlsState: 'attached' })
        hls.loadSource(url)
      })

      hls.on(Hls.Events.MANIFEST_PARSED, (_, data) => {
        console.log('[HLS] Manifest parsed, levels:', data.levels.length)
        updateDebug({ hlsState: 'manifest_parsed', videoState: 'ready' })
        setIsLoading(false)
        if (autoPlay) {
          video.play().catch(e => {
            console.warn('[HLS] Autoplay blocked:', e)
            setIsPlaying(false)
          })
        }
      })

      hls.on(Hls.Events.MANIFEST_LOADING, () => {
        updateDebug({ hlsState: 'loading_manifest' })
      })

      hls.on(Hls.Events.LEVEL_LOADED, (_, data) => {
        console.log('[HLS] Level loaded, duration:', data.details.totalduration)
      })

      hls.on(Hls.Events.FRAG_LOADED, () => {
        updateDebug({ videoState: 'buffering' })
      })

      hls.on(Hls.Events.BUFFER_APPENDED, () => {
        if (video.buffered.length > 0) {
          const bufferEnd = video.buffered.end(video.buffered.length - 1)
          updateDebug({ bufferLength: bufferEnd - video.currentTime })
        }
      })

      hls.on(Hls.Events.ERROR, (_, data) => {
        console.error('[HLS] Error:', data.type, data.details, data)
        updateDebug({ hlsState: `error_${data.type}`, error: data.details })
        
        if (data.fatal) {
          switch (data.type) {
            case Hls.ErrorTypes.NETWORK_ERROR:
              setError(`Ağ hatası: ${data.details}`)
              // Try to recover
              setTimeout(() => {
                console.log('[HLS] Attempting recovery from network error')
                hls.startLoad()
              }, 2000)
              break
            case Hls.ErrorTypes.MEDIA_ERROR:
              setError(`Medya hatası: ${data.details}`)
              console.log('[HLS] Attempting recovery from media error')
              hls.recoverMediaError()
              break
            default:
              setError(`Stream yüklenemedi: ${data.details}`)
              break
          }
          setIsLoading(false)
        }
      })

      hls.attachMedia(video)

    } else if (nativeHls && isHlsStream) {
      // Native HLS support (Safari)
      console.log('[VideoPlayer] Using native HLS')
      updateDebug({ hlsState: 'native' })
      video.src = url
      
      video.addEventListener('loadedmetadata', () => {
        setIsLoading(false)
        updateDebug({ videoState: 'ready' })
        if (autoPlay) video.play().catch(() => setIsPlaying(false))
      })
      
    } else {
      // Direct source (ts, mp4, etc.)
      console.log('[VideoPlayer] Using direct source')
      updateDebug({ hlsState: 'direct' })
      video.src = url

      const handleCanPlay = () => {
        console.log('[Video] Can play')
        setIsLoading(false)
        updateDebug({ videoState: 'ready' })
        if (autoPlay) {
          video.play().catch(e => {
            console.warn('[Video] Autoplay blocked:', e)
            setIsPlaying(false)
          })
        }
      }

      const handleError = (e: Event) => {
        const videoError = video.error
        console.error('[Video] Error:', videoError)
        let errorMsg = 'Video yüklenemedi'
        
        if (videoError) {
          switch (videoError.code) {
            case MediaError.MEDIA_ERR_ABORTED:
              errorMsg = 'Video yüklemesi iptal edildi'
              break
            case MediaError.MEDIA_ERR_NETWORK:
              errorMsg = 'Ağ hatası - Video indirilemedi'
              break
            case MediaError.MEDIA_ERR_DECODE:
              errorMsg = 'Codec hatası - Video çözümlenemedi'
              break
            case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
              errorMsg = 'Format desteklenmiyor veya CORS hatası'
              break
          }
          if (videoError.message) {
            errorMsg += `: ${videoError.message}`
          }
        }
        
        setError(errorMsg)
        updateDebug({ videoState: 'error', error: errorMsg })
        setIsLoading(false)
      }

      video.addEventListener('canplay', handleCanPlay)
      video.addEventListener('error', handleError)

      return () => {
        video.removeEventListener('canplay', handleCanPlay)
        video.removeEventListener('error', handleError)
      }
    }

    return () => {
      if (hlsRef.current) {
        hlsRef.current.destroy()
        hlsRef.current = null
      }
    }
  }, [url, autoPlay, updateDebug])

  // Video event handlers
  useEffect(() => {
    const video = videoRef.current
    if (!video) return

    const handlePlay = () => {
      setIsPlaying(true)
      updateDebug({ videoState: 'playing' })
    }
    const handlePause = () => {
      setIsPlaying(false)
      updateDebug({ videoState: 'paused' })
    }
    const handleVolumeChange = () => {
      setVolume(video.volume)
      setIsMuted(video.muted)
    }
    const handleWaiting = () => {
      updateDebug({ videoState: 'buffering' })
    }

    video.addEventListener('play', handlePlay)
    video.addEventListener('pause', handlePause)
    video.addEventListener('volumechange', handleVolumeChange)
    video.addEventListener('waiting', handleWaiting)

    return () => {
      video.removeEventListener('play', handlePlay)
      video.removeEventListener('pause', handlePause)
      video.removeEventListener('volumechange', handleVolumeChange)
      video.removeEventListener('waiting', handleWaiting)
    }
  }, [updateDebug])

  // Auto-hide controls
  useEffect(() => {
    let timeout: NodeJS.Timeout
    
    const handleMouseMove = () => {
      setShowControls(true)
      clearTimeout(timeout)
      timeout = setTimeout(() => setShowControls(false), 3000)
    }

    const container = containerRef.current
    if (container) {
      container.addEventListener('mousemove', handleMouseMove)
      container.addEventListener('mouseenter', handleMouseMove)
    }

    return () => {
      clearTimeout(timeout)
      if (container) {
        container.removeEventListener('mousemove', handleMouseMove)
        container.removeEventListener('mouseenter', handleMouseMove)
      }
    }
  }, [])

  const togglePlay = () => {
    const video = videoRef.current
    if (!video) return

    if (isPlaying) {
      video.pause()
    } else {
      video.play().catch(e => console.error('Play failed:', e))
    }
  }

  const toggleMute = () => {
    const video = videoRef.current
    if (!video) return
    video.muted = !video.muted
  }

  const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const video = videoRef.current
    if (!video) return
    const newVolume = parseFloat(e.target.value)
    video.volume = newVolume
    video.muted = newVolume === 0
  }

  const toggleFullscreen = () => {
    const container = containerRef.current
    if (!container) return

    if (!document.fullscreenElement) {
      container.requestFullscreen()
      setIsFullscreen(true)
    } else {
      document.exitFullscreen()
      setIsFullscreen(false)
    }
  }

  const handleReload = () => {
    const video = videoRef.current
    if (!video) return

    setIsLoading(true)
    setError(null)

    if (hlsRef.current) {
      hlsRef.current.destroy()
      
      const hls = new Hls({
        enableWorker: true,
        lowLatencyMode: true,
      })
      hlsRef.current = hls
      hls.loadSource(url)
      hls.attachMedia(video)
      hls.on(Hls.Events.MANIFEST_PARSED, () => {
        setIsLoading(false)
        video.play()
      })
    } else {
      video.src = url
      video.load()
      video.play().catch(() => {})
    }
  }

  return (
    <motion.div
      ref={containerRef}
      initial={{ opacity: 0, scale: 0.95 }}
      animate={{ opacity: 1, scale: 1 }}
      exit={{ opacity: 0, scale: 0.95 }}
      className="relative bg-black rounded-xl overflow-hidden group"
      style={{ aspectRatio: '16/9' }}
    >
      {/* Video Element */}
      <video
        ref={videoRef}
        className="w-full h-full object-contain"
        playsInline
        crossOrigin="anonymous"
        onClick={togglePlay}
      />

      {/* Loading Overlay */}
      <AnimatePresence>
        {isLoading && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="absolute inset-0 bg-dark-900/80 flex items-center justify-center"
          >
            <div className="text-center">
              <RefreshCw className="w-12 h-12 text-accent-blue spinner mx-auto" />
              <p className="text-dark-300 mt-3">Yayın yükleniyor...</p>
              <p className="text-dark-500 text-xs mt-1">{debugInfo.hlsState}</p>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Error Overlay */}
      <AnimatePresence>
        {error && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="absolute inset-0 bg-dark-900/90 flex items-center justify-center"
          >
            <div className="text-center max-w-md px-4">
              <AlertCircle className="w-12 h-12 text-accent-red mx-auto" />
              <p className="text-accent-red mt-3 font-medium">{error}</p>
              <p className="text-dark-400 text-xs mt-2 break-all">{url}</p>
              <div className="flex gap-2 justify-center mt-4">
                <button
                  onClick={handleReload}
                  className="px-4 py-2 bg-accent-blue text-white rounded-lg hover:bg-accent-blue/80 transition-colors flex items-center gap-2"
                >
                  <RefreshCw className="w-4 h-4" />
                  Tekrar Dene
                </button>
                <button
                  onClick={() => setShowDebug(!showDebug)}
                  className="px-4 py-2 bg-dark-700 text-dark-300 rounded-lg hover:bg-dark-600 transition-colors flex items-center gap-2"
                >
                  <Bug className="w-4 h-4" />
                  Debug
                </button>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Debug Panel */}
      <AnimatePresence>
        {showDebug && (
          <motion.div
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            exit={{ opacity: 0, x: 20 }}
            className="absolute top-12 right-4 bg-dark-900/95 border border-dark-600 rounded-lg p-4 text-xs font-mono max-w-xs z-50"
          >
            <div className="flex items-center justify-between mb-2">
              <span className="text-accent-blue font-semibold">Debug Info</span>
              <button onClick={() => setShowDebug(false)} className="text-dark-400 hover:text-white">
                <X className="w-4 h-4" />
              </button>
            </div>
            <div className="space-y-1 text-dark-300">
              <p><span className="text-dark-500">HLS.js:</span> {debugInfo.hlsSupported ? '✅' : '❌'}</p>
              <p><span className="text-dark-500">Native HLS:</span> {debugInfo.nativeHlsSupported ? '✅' : '❌'}</p>
              <p><span className="text-dark-500">State:</span> {debugInfo.hlsState}</p>
              <p><span className="text-dark-500">Video:</span> {debugInfo.videoState}</p>
              <p><span className="text-dark-500">Buffer:</span> {debugInfo.bufferLength.toFixed(1)}s</p>
              {debugInfo.error && (
                <p className="text-accent-red"><span className="text-dark-500">Error:</span> {debugInfo.error}</p>
              )}
              <p className="text-dark-500 break-all mt-2">URL: {debugInfo.url.substring(0, 50)}...</p>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Controls Overlay */}
      <AnimatePresence>
        {showControls && !isLoading && !error && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-black/40"
          >
            {/* Top Bar */}
            <div className="absolute top-0 left-0 right-0 p-4 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Tv2 className="w-5 h-5 text-accent-red" />
                <span className="text-white font-medium">{title}</span>
                <span className="px-2 py-0.5 bg-accent-red text-white text-xs rounded">CANLI</span>
              </div>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setShowDebug(!showDebug)}
                  className={`p-2 rounded-lg transition-colors ${showDebug ? 'bg-accent-blue/30 text-accent-blue' : 'bg-dark-800/50 hover:bg-dark-700 text-white'}`}
                  title="Debug Paneli"
                >
                  <Bug className="w-4 h-4" />
                </button>
                {onClose && (
                  <button
                    onClick={onClose}
                    className="p-2 rounded-lg bg-dark-800/50 hover:bg-dark-700 transition-colors"
                  >
                    <X className="w-5 h-5 text-white" />
                  </button>
                )}
              </div>
            </div>

            {/* Center Play Button */}
            {!isPlaying && (
              <button
                onClick={togglePlay}
                className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-20 h-20 rounded-full bg-accent-blue/80 hover:bg-accent-blue flex items-center justify-center transition-colors"
              >
                <Play className="w-10 h-10 text-white ml-1" fill="white" />
              </button>
            )}

            {/* Bottom Controls */}
            <div className="absolute bottom-0 left-0 right-0 p-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  {/* Play/Pause */}
                  <button
                    onClick={togglePlay}
                    className="p-2 rounded-lg bg-dark-800/50 hover:bg-dark-700 transition-colors"
                  >
                    {isPlaying ? (
                      <Pause className="w-5 h-5 text-white" />
                    ) : (
                      <Play className="w-5 h-5 text-white" />
                    )}
                  </button>

                  {/* Volume */}
                  <div className="flex items-center gap-2">
                    <button
                      onClick={toggleMute}
                      className="p-2 rounded-lg bg-dark-800/50 hover:bg-dark-700 transition-colors"
                    >
                      {isMuted || volume === 0 ? (
                        <VolumeX className="w-5 h-5 text-white" />
                      ) : (
                        <Volume2 className="w-5 h-5 text-white" />
                      )}
                    </button>
                    <input
                      type="range"
                      min="0"
                      max="1"
                      step="0.1"
                      value={isMuted ? 0 : volume}
                      onChange={handleVolumeChange}
                      className="w-20 h-1 bg-dark-600 rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full"
                    />
                  </div>

                  {/* Reload */}
                  <button
                    onClick={handleReload}
                    className="p-2 rounded-lg bg-dark-800/50 hover:bg-dark-700 transition-colors"
                    title="Yeniden Yükle"
                  >
                    <RefreshCw className="w-5 h-5 text-white" />
                  </button>
                </div>

                {/* Fullscreen */}
                <button
                  onClick={toggleFullscreen}
                  className="p-2 rounded-lg bg-dark-800/50 hover:bg-dark-700 transition-colors"
                >
                  {isFullscreen ? (
                    <Minimize className="w-5 h-5 text-white" />
                  ) : (
                    <Maximize className="w-5 h-5 text-white" />
                  )}
                </button>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  )
}
