"use client";
import React, { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import { createPortal } from "react-dom";

const ReactPlayer = dynamic(() => import("react-player"), { ssr: false }) as any;

interface VideoModalProps {
  isOpen: boolean;
  onClose: () => void;
  videoUrl: string;
  title?: string;
}

export default function VideoModal({
  isOpen,
  onClose,
  videoUrl,
  title = "Video popup",
}: VideoModalProps) {
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  if (!isOpen || !isMounted) {
    return null;
  }

  return createPortal(
    <div
      role="dialog"
      aria-modal="true"
      aria-label={title}
      onClick={onClose}
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 9999,
        backgroundColor: "rgba(0, 0, 0, 0.8)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: "24px",
      }}
    >
      <div
        onClick={(event) => event.stopPropagation()}
        style={{
          width: "100%",
          maxWidth: "900px",
          position: "relative",
        }}
      >
        <button
          type="button"
          onClick={onClose}
          aria-label="Close video popup"
          style={{
            position: "absolute",
            top: "-44px",
            right: "0",
            border: 0,
            background: "transparent",
            color: "#fff",
            fontSize: "32px",
            lineHeight: 1,
            cursor: "pointer",
          }}
        >
          &times;
        </button>
        <div
          style={{
            position: "relative",
            paddingTop: "56.25%",
            borderRadius: "8px",
            overflow: "hidden",
          }}
        >
          <ReactPlayer
            src={videoUrl}
            controls
            playing
            width="100%"
            height="100%"
            style={{ position: "absolute", top: 0, left: 0 }}
          />
        </div>
      </div>
    </div>,
    document.body
  );
}
