import { Box, Typography } from "@mui/material";
import { useState, useEffect } from "react";
import { Cuboid } from "lucide-react";

import { ReactPhotoSphereViewer } from "react-photo-sphere-viewer";
import { ThreeView } from "./ThreeView";
import { ThreeViewErrorBoundary } from "./ThreeViewErrorBoundary";
import { clearMediaTransitionCache } from "../../shared/lib/gltfCacheManager";

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

export function MediaViewer({
  media,
  className,
  height,
  width,
  fullWidth,
  fullHeight,
  compact,
}: Readonly<{
  media?: MediaData;
  className?: string;
  height?: string;
  width?: string;
  fullWidth?: boolean;
  fullHeight?: boolean;
  /** В компактном режиме (миниатюры) 3D модели не рендерятся — показывается placeholder */
  compact?: boolean;
}>) {
  const token = localStorage.getItem("token");
  const [resetKey, setResetKey] = useState(0);
  const [previousMediaId, setPreviousMediaId] = useState<
    string | number | null
  >(null);

  useEffect(() => {
    if (media?.id !== previousMediaId) {
      // Используем новый cache manager для очистки кеша
      clearMediaTransitionCache(
        previousMediaId,

        media?.media_type
      );

      setResetKey(0);
      setPreviousMediaId(media?.id || null);
    }
  }, [media?.id, media?.media_type, previousMediaId]);

  const handleReset = () => {
    setResetKey((prev) => {
      const newKey = prev + 1;

      return newKey;
    });
  };

  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: compact ? "80px" : fullHeight ? "100%" : height ? height : "auto",
            width: compact ? "100px" : fullWidth ? "100%" : width ? width : "auto",
            objectFit: "cover",
          }}
        />
      )}

      {media?.media_type === 2 && (
        <video
          src={`${import.meta.env.VITE_KRBL_MEDIA}${
            media?.id
          }/download?token=${token}`}
          style={{
            width: compact ? "100px" : width ? width : "100%",
            height: compact ? "80px" : height ? 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: compact ? "80px" : fullHeight ? "100%" : height ? height : "auto",
            width: compact ? "100px" : fullWidth ? "100%" : width ? width : "auto",
            objectFit: "cover",
          }}
        />
      )}
      {media?.media_type === 4 && (
        <img
          src={`${import.meta.env.VITE_KRBL_MEDIA}${
            media?.id
          }/download?token=${token}`}
          alt={media?.filename}
          style={{
            width: compact ? "100px" : "100%",
            height: compact ? "80px" : undefined,
            objectFit: "cover",
          }}
        />
      )}

      {media?.media_type === 5 && (
        <ReactPhotoSphereViewer
          src={`${import.meta.env.VITE_KRBL_MEDIA}${
            media?.id
          }/download?token=${token}`}
          width={compact ? "100px" : fullWidth ? "100%" : width ? width : "500px"}
          height={compact ? "80px" : fullHeight ? "100%" : height ? height : "300px"}
        />
      )}

      {media?.media_type === 6 &&
        (compact ? (
          <Box
            sx={{
              width: "100px",
              height: "80px",
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
              justifyContent: "center",
              backgroundColor: "action.hover",
              borderRadius: 5,
              color: "text.secondary",
            }}
          >
            <Cuboid size={24} />
            <Typography variant="caption" sx={{ mt: 0.5 }}>
              3D
            </Typography>
          </Box>
        ) : (
          <ThreeViewErrorBoundary
            onReset={handleReset}
            resetKey={`${media?.id}-${resetKey}`}
          >
            <ThreeView
              key={`3d-model-${media?.id}-${resetKey}`}
              fileUrl={`${import.meta.env.VITE_KRBL_MEDIA}${
                media?.id
              }/download?token=${token}`}
              height={height ? height : "500px"}
              width={width ? width : "500px"}
            />
          </ThreeViewErrorBoundary>
        ))}
    </Box>
  );
}
