import cn from "classnames";
import React, { useRef } from "react";
import { ReactPhotoSphereViewer } from "react-photo-sphere-viewer";

import { PhotoSphereLightboxData } from "@mt/common-types";

import "./AttractionMedia.css";
import { useLightboxContext } from "../../lightbox";
import { Icons } from "@mt/components";

interface PhotoSphereMediaProps {
  url: string;
  watermarkUrl?: string;
}

export const PhotoSphereMedia = ({
  url,
  watermarkUrl,
}: PhotoSphereMediaProps) => {
  // prettier-ignore
  const { setData, openLightbox } = useLightboxContext<PhotoSphereLightboxData>();
  // react-photo-sphere-viewer doesn't have exported types, so here's a bit of a hardcoded piece
  const photoSphereRef = useRef<any>(null);

  const handlePhotoSphereFullscreenOpen = () => {
    photoSphereRef.current?.stopAutoRotate();
    setData({
      type: "PHOTO_SPHERE",
      imageUrl: url,
      watermarkUrl,
    });
    openLightbox();
  };

  return (
    <div className="widget-media__wrapper">
      <ReactPhotoSphereViewer
        ref={photoSphereRef}
        key={url}
        src={url}
        height={"350px"}
        width={"100%"}
        container={cn("widget-media", {
          "media-with-watermark": watermarkUrl !== null,
        })}
        moveInertia={false}
        mousemove={true}
        navbar={["autorotate", "zoom"]}
        keyboard={false}
        loadingTxt="Загрузка..."
      />
      {watermarkUrl && (
        <img src={watermarkUrl} alt="Watermark" className="watermark" />
      )}
      {/* the following is a workaround to open lightbox-like preview in the middle of the screen instead of the real fullscreen */}
      <Icons.FullscreenIcon
        className="fullscreen-photo-sphere-btn"
        onPointerUp={() => handlePhotoSphereFullscreenOpen()}
      />
    </div>
  );
};
