"use client";

import { useState, useEffect } from "react";
import { useLanguage } from "@/contexts/LanguageContext";
import { contentVideosApi, ContentVideoPublic } from "@/lib/api";
import { Youtube, Play, X } from "lucide-react";

interface YouTubeVideoDisplayProps {
  entityType: "project" | "solution" | "product";
  entityId: number;
}

export default function YouTubeVideoDisplay({
  entityType,
  entityId,
}: YouTubeVideoDisplayProps) {
  const { locale } = useLanguage();
  const [videos, setVideos] = useState<ContentVideoPublic[]>([]);
  const [loading, setLoading] = useState(true);
  const [playingVideo, setPlayingVideo] = useState<ContentVideoPublic | null>(null);

  useEffect(() => {
    const fetchVideos = async () => {
      try {
        const data = await contentVideosApi.getForEntity(entityType, entityId, locale);
        setVideos(data);
      } catch (error) {
        console.error("Failed to fetch videos:", error);
      } finally {
        setLoading(false);
      }
    };

    fetchVideos();
  }, [entityType, entityId, locale]);

  if (loading || videos.length === 0) {
    return null;
  }

  return (
    <>
      {/* Video Section */}
      <div className="mt-12">
        <div className="flex items-center gap-2 mb-6">
          <Youtube className="w-6 h-6 text-red-500" />
          <h3 className="text-xl font-bold text-gray-900">
            {locale === "ko" ? "관련 영상" :
             locale === "en" ? "Related Videos" :
             locale === "ja" ? "関連動画" : "相关视频"}
          </h3>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {videos.map((video) => (
            <div
              key={video.id}
              className="group relative bg-gray-100 rounded-xl overflow-hidden cursor-pointer"
              onClick={() => setPlayingVideo(video)}
            >
              {/* Thumbnail */}
              <div className="aspect-video relative">
                <img
                  src={video.thumbnail_url}
                  alt={video.title}
                  className="w-full h-full object-cover transition-transform group-hover:scale-105"
                  onError={(e) => {
                    (e.target as HTMLImageElement).src =
                      `https://img.youtube.com/vi/${video.youtube_id}/hqdefault.jpg`;
                  }}
                />
                {/* Play button overlay */}
                <div className="absolute inset-0 flex items-center justify-center bg-black/20 group-hover:bg-black/40 transition-colors">
                  <div className="w-16 h-16 bg-red-500 rounded-full flex items-center justify-center shadow-lg transform group-hover:scale-110 transition-transform">
                    <Play className="w-8 h-8 text-white ml-1" fill="white" />
                  </div>
                </div>
              </div>
              {/* Title */}
              <div className="p-3">
                <h4 className="font-medium text-gray-900 line-clamp-2">
                  {video.title}
                </h4>
                {video.description && (
                  <p className="text-sm text-gray-500 mt-1 line-clamp-2">
                    {video.description}
                  </p>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Video Modal */}
      {playingVideo && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/80"
          onClick={() => setPlayingVideo(null)}
        >
          <div
            className="relative w-full max-w-4xl mx-4"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Close button */}
            <button
              onClick={() => setPlayingVideo(null)}
              className="absolute -top-12 right-0 text-white hover:text-gray-300 transition"
            >
              <X className="w-8 h-8" />
            </button>

            {/* Video iframe */}
            <div className="aspect-video bg-black rounded-lg overflow-hidden">
              <iframe
                src={`${playingVideo.youtube_embed_url}?autoplay=1`}
                title={playingVideo.title}
                className="w-full h-full"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen
              />
            </div>

            {/* Video title */}
            <div className="mt-4 text-white">
              <h3 className="text-xl font-semibold">{playingVideo.title}</h3>
              {playingVideo.description && (
                <p className="text-gray-300 mt-2">{playingVideo.description}</p>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}
