import { Box } from "@mui/material";

import { ReactPhotoSphereViewer } from "react-photo-sphere-viewer";
import { ThreeView } from "./ThreeView";

export interface MediaData {
  id: string | number;
  media_type: number;
  filename?: string;
}

export function MediaViewer({
  media,
  className,
  fullWidth,
  fullHeight,
}: Readonly<{
  media?: MediaData;
  className?: string;
  fullWidth?: boolean;
  fullHeight?: boolean;
}>) {
  const token = localStorage.getItem("token");
  return (
    <Box
      className={className}
      sx={{
        width: fullWidth ? "100%" : "auto",
        height: fullHeight ? "100%" : "auto",
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        overflow: "hidden",
      }}
      width={fullWidth ? "100%" : "auto"}
      height={fullHeight ? "100%" : "auto"}
    >
      {media?.media_type === 1 && (
        <img
          src={`${import.meta.env.VITE_KRBL_MEDIA}${
            media?.id
          }/download?token=${token}`}
          alt={media?.filename}
          style={{
            height: fullHeight ? "100%" : "auto",
            width: fullWidth ? "100%" : "auto",
            ...(media?.filename?.toLowerCase().endsWith(".webp") && {
              maxWidth: "300px",
              maxHeight: "300px",
              objectFit: "contain",
            }),
          }}
        />
      )}

      {media?.media_type === 2 && (
        <video
          src={`${import.meta.env.VITE_KRBL_MEDIA}${
            media?.id
          }/download?token=${token}`}
          style={{
            width: "100%",
            height: "100%",
            objectFit: "cover",
            borderRadius: 8,
          }}
          controls
          autoPlay
          muted
        />
      )}
      {media?.media_type === 3 && (
        <img
          src={`${import.meta.env.VITE_KRBL_MEDIA}${
            media?.id
          }/download?token=${token}`}
          alt={media?.filename}
          style={{
            height: fullHeight ? "100%" : "auto",
            width: fullWidth ? "100%" : "auto",
          }}
        />
      )}
      {media?.media_type === 4 && (
        <img
          src={`${import.meta.env.VITE_KRBL_MEDIA}${
            media?.id
          }/download?token=${token}`}
          alt={media?.filename}
          style={{
            objectFit: "cover",
          }}
        />
      )}

      {media?.media_type === 5 && (
        <ReactPhotoSphereViewer
          src={`${import.meta.env.VITE_KRBL_MEDIA}${
            media?.id
          }/download?token=${token}`}
          width={"100%"}
          height={"100%"}
        />
      )}

      {media?.media_type === 6 && (
        <ThreeView
          fileUrl={`${import.meta.env.VITE_KRBL_MEDIA}${
            media?.id
          }/download?token=${token}`}
          height="500px"
          width="500px"
        />
      )}
    </Box>
  );
}
