import React, { useState } from "react";
import { ContentfulVideoEmbed } from "./contentful-video-embed";
import { PlayButton } from "./helper";
import { VideoLinkComponentProps } from "./types";
import { VimeoEmbed } from "./vimeo-embed";
import { YoutubeEmbed } from "./youtube-embed";

import { NextImage } from "@shared/components/next-image";
import { cx } from "@shared/utils";

// Owns all video state (active/hover) so ImagePromoBar stays state-free for video.
export const VideoLink: React.FC<VideoLinkComponentProps> = ({
  videoLink,
  imageWidth = 660,
  imageHeight = 660,
  useOriginalImageAspectRatio = false,
  isAboveTheFold = false,
}) => {
  const [activeVideo, setActiveVideo] = useState("");
  const [isHovered, setIsHovered] = useState(false);

  const videoSourceType = videoLink?.videoSourceType;
  const videoHref =
    (videoSourceType === "contentful"
      ? videoLink?.videoAssetUrl
      : videoLink?.link) ?? "";

  // The video's own poster - never the promo bar's plain image field.
  const posterImage = videoLink?.image;

  if (!videoHref) {
    if (!posterImage) {
      return null;
    }
    return (
      <div
        className={cx(
          !useOriginalImageAspectRatio
            ? "relative aspect-[16/9] w-full overflow-hidden rounded-image lg:h-[486px] xl:aspect-square xl:max-h-[486px] xl:w-[486px]"
            : "overflow-hidden rounded-image"
        )}
      >
        <NextImage
          src={posterImage}
          alt="section-image"
          priority={isAboveTheFold}
          fill={!useOriginalImageAspectRatio}
          width={!useOriginalImageAspectRatio ? undefined : imageWidth || 660}
          height={!useOriginalImageAspectRatio ? undefined : imageHeight || 660}
          sizes="(max-width: 430px) 100vw, (max-width: 834px) 100vw, 50vw"
          className={cx(
            !useOriginalImageAspectRatio ? "object-cover" : "w-full"
          )}
        />
      </div>
    );
  }

  const videoPopup = videoLink?.videoPopup ?? false;
  const isPlaying = Boolean(activeVideo && activeVideo === videoHref);

  const handlePlayClick = () => {
    setActiveVideo(videoHref);
  };

  const handleCloseVideo = (e: React.MouseEvent) => {
    e.stopPropagation();
    setActiveVideo("");
  };

  const embedSelector = () => {
    if (videoSourceType === "contentful") {
      return (
        <ContentfulVideoEmbed
          videoAssetUrl={videoLink?.videoAssetUrl}
          videoAssetType={videoLink?.videoAssetType}
          image={posterImage}
          title={videoLink?.title}
          description={videoLink?.description}
          autoplay={isPlaying}
        />
      );
    }
    if (videoHref.includes("vimeo")) {
      return <VimeoEmbed link={videoHref} autoplay={isPlaying} />;
    }
    return <YoutubeEmbed link={videoHref} autoplay={isPlaying} />;
  };
  const contentVideo = embedSelector();

  return (
    <>
      <div
        className={cx(
          "video-section relative w-full cursor-pointer rounded-image transition-all duration-300 lg:w-[486px]",
          !isPlaying && "hover:ring-2 hover:ring-border-focus"
        )}
        onClick={handlePlayClick}
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
      >
        {/* Preview Image & Play Button */}
        <div
          className={cx(
            isPlaying && !videoPopup && "hidden",
            isPlaying && !videoPopup ? "opacity-0" : "opacity-100",
            "relative w-full transition-opacity duration-300"
          )}
        >
          {posterImage && (
            <NextImage
              src={posterImage}
              alt="Video preview"
              width={imageWidth || 660}
              height={imageHeight || 660}
              sizes="(max-width: 430px) 100vw, (max-width: 834px) 100vw, 50vw"
              className="h-auto w-full rounded-image"
            />
          )}
          <div className="absolute inset-0 flex items-center justify-center">
            <PlayButton isHovered={isHovered} />
          </div>
        </div>

        {/* Inline Player (if not popup) */}
        {!videoPopup && isPlaying && (
          <div
            className={cx(
              "aspect-[16/9] w-full overflow-hidden rounded-image transition-opacity duration-300",
              isPlaying ? "opacity-100" : "opacity-0",
              !useOriginalImageAspectRatio &&
                "xl:aspect-square xl:max-h-[486px] xl:w-[486px]"
            )}
          >
            {contentVideo}
          </div>
        )}
      </div>

      {/* Video Popup Overlay */}
      {videoPopup && isPlaying && (
        <div
          className="fixed inset-0 top-20 z-[100] flex items-center justify-center bg-black/80 p-4 transition-all duration-300"
          onClick={handleCloseVideo}
        >
          <div
            className="max-w-6xl aspect-video w-full overflow-hidden rounded-3xl bg-black shadow-2xl md:w-4/6"
            onClick={e => e.stopPropagation()}
          >
            {contentVideo}
          </div>
        </div>
      )}
    </>
  );
};

export default VideoLink;

export { ContentfulVideoEmbed } from "./contentful-video-embed";
export { PlayButton } from "./helper";
export { VimeoEmbed } from "./vimeo-embed";
export { YoutubeEmbed } from "./youtube-embed";

export type {
  PlayButtonProps,
  VideoEmbedProps,
  VideoLinkComponentProps,
  VideoLinkProps,
} from "./types";
