"use client";

import React, { useEffect } from "react";
import Link from "next/link";
import { BlogPost, extractYouTubeId } from "@/services/blogService";
import { X, Play, Clock, Eye, Sparkles, ExternalLink, ArrowRight, CheckCircle2 } from "lucide-react";

interface VideoPlayerModalProps {
  post: BlogPost | null;
  isOpen: boolean;
  onClose: () => void;
}

export default function VideoPlayerModal({ post, isOpen, onClose }: VideoPlayerModalProps) {
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape" && isOpen) {
        onClose();
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [isOpen, onClose]);

  if (!isOpen || !post) return null;

  const ytId = post.youtube_id || extractYouTubeId(post.youtube_url) || "0m_kO8c4VzI";

  return (
    <div 
      className="fixed inset-0 z-50 overflow-y-auto bg-black/85 backdrop-blur-md flex items-center justify-center p-3 sm:p-6 animate-in fade-in duration-200"
      onClick={onClose}
    >
      <div 
        className="bg-[#11121f] border border-white/15 rounded-3xl max-w-4xl w-full overflow-hidden shadow-2xl relative animate-in zoom-in-95 duration-200"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Top Bar with Title & Close Button */}
        <div className="p-4 sm:px-6 flex items-center justify-between border-b border-white/10 bg-[#0d0e1a]">
          <div className="flex items-center gap-2.5 min-w-0 pr-4">
            <span className="w-2.5 h-2.5 rounded-full bg-red-500 animate-pulse shrink-0" />
            <span className="px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-[#4223de] text-white shrink-0">
              {post.category?.name || post.category_name || "Video Tour"}
            </span>
            <h3 className="text-white text-xs sm:text-sm font-bold truncate">
              {post.title}
            </h3>
          </div>

          <button
            onClick={onClose}
            className="w-9 h-9 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition-colors shrink-0 cursor-pointer"
            title="Close Video"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* 16:9 YouTube Zero-Redirect Live Player Container */}
        <div className="relative aspect-[16/9] w-full bg-black">
          <iframe
            src={`https://www.youtube-nocookie.com/embed/${ytId}?autoplay=1&rel=0&modestbranding=1&enablejsapi=1`}
            title={post.title}
            className="w-full h-full"
            frameBorder="0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
            allowFullScreen
          />
        </div>

        {/* Bottom Details Bar */}
        <div className="p-5 sm:p-6 bg-[#11121f] space-y-4">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
            <div className="flex items-center gap-3">
              <img
                src={post.author?.avatar}
                alt={post.author?.name}
                className="w-10 h-10 rounded-full object-cover border-2 border-[#4223de]"
                onError={(e) => {
                  (e.currentTarget as HTMLImageElement).src = "https://images.unsplash.com/photo-1560250097-0b93528c311a?auto=format&fit=crop&w=256&q=80";
                }}
              />
              <div>
                <strong className="text-white block font-bold text-xs sm:text-sm">{post.author?.name}</strong>
                <span className="text-slate-400 text-[11px]">{post.author_role}</span>
              </div>
            </div>

            <div className="flex items-center gap-3 text-xs text-slate-400 font-medium">
              {post.duration && (
                <span className="flex items-center gap-1 bg-white/10 px-3 py-1 rounded-full text-white font-mono text-[11px]">
                  <Clock className="w-3.5 h-3.5 text-[#deddfc]" />
                  <span>{post.duration}</span>
                </span>
              )}
              {post.view_count !== undefined && post.view_count > 0 && (
                <span className="flex items-center gap-1 bg-white/5 px-3 py-1 rounded-full text-slate-300">
                  <Eye className="w-3.5 h-3.5 text-[#deddfc]" />
                  <span>{post.view_count.toLocaleString()} Views</span>
                </span>
              )}
              <Link
                href={`/insights/${post.slug}`}
                onClick={onClose}
                className="bg-[#4223de] hover:bg-[#3912d8] text-white font-bold px-4 py-1.5 rounded-full text-xs transition-all flex items-center gap-1.5 shadow-md shadow-[#4223de]/30 cursor-pointer"
              >
                <span>Read Full Briefing</span>
                <ArrowRight className="w-3.5 h-3.5" />
              </Link>
            </div>
          </div>

          {post.excerpt && (
            <p className="text-slate-300 text-xs sm:text-sm leading-relaxed line-clamp-2 border-t border-white/10 pt-3">
              {post.excerpt}
            </p>
          )}
        </div>

      </div>
    </div>
  );
}
