import React, { useEffect, useRef, useState } from "react";
import VideoButton from "../buttons/VideoButton.jsx";
import Link from "next/link";

function Section({
  videoUrl,
  videoUrlWeb,
  text,
  headingLevel = 1,
  buttonVideoURL,
  buttonOneText,
  buttonTwoText,
  buttonLink,
  posterPath,
}) {
  const videoRef = useRef(null);
  const [isPlaying, setIsPlaying] = useState(false);

  useEffect(() => {
    const playPromise = videoRef.current?.play();

    if (playPromise) {
      playPromise
        .then(() => {
          setIsPlaying(true);
        })
        .catch((error) => {
          console.error("Play error:", error);
        });
    }

    return () => {
      if (videoRef.current) {
        videoRef.current.pause();
      }
    };
  }, []);

  if (headingLevel <= 0 || headingLevel >= 7) {
    throw new Error("Invalid heading level");
  }

  const Heading = `h${headingLevel}`;

  return (
    <div className="relative z-10 h-screen w-screen bg-black">
      <video
        className="absolute h-screen w-screen object-cover blur-sm"
        poster={posterPath}
        ref={videoRef}
        muted
        autoPlay
        loop
        preload="metadata"
      >
        <source src={videoUrlWeb} type="video/webm" />
        <source src={videoUrl} type="video/mp4" />
        Your browser does not support the video tag.
      </video>
      <div className="relative z-10 flex flex-col items-center justify-center h-full">
        <div className="flex flex-col items-center space-y-4">
          <Heading className="lg:text-5xl md:text-4xl sm:text-3xl text-3xl text-center text-white break-normal">
            {text}
          </Heading>
          <div className="flex flex-col sm:flex-row sm:space-x-4 items-center justify-center">
            <VideoButton
              buttonVideoURL={buttonVideoURL}
              buttonOneText={buttonOneText}
            />
            <Link
              href={buttonLink}
              id="ButtonLink"
              className="mt-8 px-4 py-2 text-white"
            >
              {buttonTwoText}
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Section;
