import { useEffect, useRef } from 'react'
import { Video } from '../data/videos'

interface VideoModalProps {
  video: Video | null
  onClose: () => void
}

export default function VideoModal({ video, onClose }: VideoModalProps) {
  const videoRef = useRef<HTMLVideoElement>(null)

  useEffect(() => {
    if (video && videoRef.current) {
      videoRef.current.play()
    }
  }, [video])

  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', handleEscape)
    return () => document.removeEventListener('keydown', handleEscape)
  }, [onClose])

  if (!video) return null

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
      onClick={onClose}
    >
      <div
        className="relative w-full max-w-4xl bg-[#1a1a2e] rounded-2xl overflow-hidden animate-fade-in-up"
        onClick={(e) => e.stopPropagation()}
      >
        <button
          onClick={onClose}
          className="absolute top-4 right-4 z-10 w-10 h-10 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center transition-colors"
        >
          <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>

        <div className="aspect-video">
          <video
            ref={videoRef}
            src={video.url}
            controls
            className="w-full h-full"
            poster={video.thumbnail}
          >
            您的浏览器不支持视频播放
          </video>
        </div>

        <div className="p-6">
          <div className="flex items-center gap-3 mb-2">
            <h2 className="text-2xl font-bold text-white">{video.title}</h2>
            <span className="px-3 py-1 rounded-full text-sm gradient-bg">
              {video.category}
            </span>
          </div>
          <p className="text-gray-400">{video.description}</p>
        </div>
      </div>
    </div>
  )
}
