import { Box } from "@mui/material";
import { getVideo } from "./helper";
import type { SxProps } from "@mui/material";
import useSWR from "swr";
import LoadingSkeleton from "../LoadingSkeleton";
import { ApologyPage } from "@/components/ViewPublicationPage/ApologyPage";

type VideoIframeProps = {
  videoUrl: string;
  containerSX?: SxProps;
};

export default function QuizVideo({ videoUrl, containerSX }: VideoIframeProps) {
  console.log("=== QuizVideo component called ===");
  console.log("QuizVideo component called with URL:", videoUrl);
  console.log("ContainerSX:", containerSX);

  const { data: videoData, error, isLoading } = useSWR(["video", videoUrl], (params) => getVideo(params[1]));

  console.log("Video data:", videoData);
  console.log("Error:", error);
  console.log("Is loading:", isLoading);
  console.log("=== End QuizVideo component ===");

  return (
    <Box
      id="test-video-container"
      sx={{
        width: "100%",
        height: "100%",
        minHeight: videoData?.sourceName === "tiktok" ? "740px" : 0,
        "& iframe": { width: "100%", height: "100%" },
        ...containerSX,
      }}
    >
      {isLoading ? (
        <LoadingSkeleton />
      ) : !videoData || error ? (
        <ApologyPage error={error ?? new Error()} />
      ) : videoData.sourceName === "custom" || videoData.sourceName === "yandex" ? (
        <Box
          component="video"
          sx={{ width: "100%", height: "100%" }}
          autoPlay
          controls
          muted
          loop
          playsInline
          onError={(e) => console.error("Video error:", e)}
          onLoadStart={() => console.log("Video load started")}
          onCanPlay={() => console.log("Video can play")}
          src={videoData.url}
        />
      ) : (
        <Box
          component="iframe"
          src={videoData.url}
          title={videoData.sourceName}
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
          {...{ allowFullScreen: true, frameBorder: 0 }}
        />
      )}
    </Box>
  );
}
