import { JaaSMeeting } from "@jitsi/react-sdk";
import { useQuery } from "@tanstack/react-query";
import random from "randomstring";
import { v4 as uuid } from "uuid";
import { useMemo, useState } from "react";
import { Textfit } from "react-textfit";
import makeRequest, {
  makeFormData,
  VideoMeetingJWTResponse,
} from "../../../Ajax";
import useBaseElementStyles from "./hooks/useBaseElementStyles";
import useEditableFeatures from "./hooks/useEditableFeatures";
import {
  ElementComponent,
  ElementProps,
  ElementTypeName,
  ShowHideDefaultVisibility,
  VideoMeetingElementData,
} from "./types";
import VideoMeetingInfoDialog from "./VideoMeetingInfoDialog";

const APP_ID = "vpaas-magic-cookie-3f8fc75203ac4dbfb542b999bbd91d63";

function VideoMeeting(props: ElementProps<VideoMeetingElementData>) {
  const { resizeHandles, moveListeners, currentDimensions } =
    useEditableFeatures(props);
  const { baseClasses, baseStyles } = useBaseElementStyles(
    currentDimensions,
    props.scaleFactor,
    props.isEditable,
  );

  const {
    sessionName: originalSessionName,
    sessionPassword,
    id,
    width,
    height,
  } = props.element;
  const { isEditable, scaleFactor } = props;
  const sessionName = originalSessionName
    .split(/[^a-zA-Z0-9]/)
    .filter((s) => s.length)
    .join("-");

  const [joinDialogOpen, setJoinDialogOpen] = useState<boolean>(false);
  const [userInfo, setUserInfo] = useState<null | {
    name: string;
    email: string;
  }>(null);

  const jwtQuery = useQuery(
    ["video-meeting-jwt", id],
    () =>
      makeRequest<VideoMeetingJWTResponse>(
        "internal/publication/create_jitsi_signature/",
        "POST",
        {
          roomName: sessionName,
          userID: uuid(),
          userName: userInfo.name,
          userEmail: userInfo.email,
        },
      ),
    {
      enabled: userInfo !== null,
    },
  );

  const insideContents = useMemo(() => {
    if (isEditable || window.location.hostname === "admin.cloud-screen.com") {
      return (
        <Textfit
          mode="multi"
          style={{
            backgroundColor: "#ccc",
            border: "1px solid black",
            position: "absolute",
            width: "100%",
            height: "100%",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            textAlign: "center",
          }}
        >
          Video Meeting will display here in the publication
        </Textfit>
      );
    }

    if (userInfo === null) {
      return (
        <>
          <VideoMeetingInfoDialog
            elementId={id}
            showDialog={joinDialogOpen}
            onSuccessfulClose={(name, email) => setUserInfo({ name, email })}
            onBadClose={() => setJoinDialogOpen(false)}
            sessionPassword={sessionPassword}
          />
          <Textfit
            mode="multi"
            onClick={() => setJoinDialogOpen(true)}
            style={{
              backgroundColor: "#ccc",
              border: "1px solid black",
              position: "absolute",
              width: "100%",
              height: "100%",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              textAlign: "center",
              cursor: "pointer",
            }}
          >
            Click here to join the meeting
          </Textfit>
        </>
      );
    }

    if (!jwtQuery.isSuccess) {
      return (
        <Textfit
          mode="multi"
          style={{
            backgroundColor: "#ccc",
            border: "1px solid black",
            position: "absolute",
            width: "100%",
            height: "100%",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            textAlign: "center",
          }}
        >
          Loading...
        </Textfit>
      );
    }

    return (
      <JaaSMeeting
        appId={APP_ID}
        roomName={sessionName}
        jwt={jwtQuery.data.data.token}
        configOverwrite={{
          disableThirdPartyRequests: true,
          disableLocalVideoFlip: true,
          backgroundAlpha: 0.5,
        }}
        interfaceConfigOverwrite={{
          VIDEO_LAYOUT_FIT: "nocrop",
          MOBILE_APP_PROMO: false,
          TILE_VIEW_MAX_COLUMNS: 4,
        }}
        onApiReady={(api) =>
          (api.getIFrame().parentElement.style.height = "100%")
        }
      />
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    id,
    isEditable,
    joinDialogOpen,
    scaleFactor,
    sessionName,
    sessionPassword,
    width,
    height,
    jwtQuery,
  ]);

  return (
    <div
      className={baseClasses}
      style={{
        ...baseStyles,
      }}
      {...moveListeners}
    >
      {insideContents}
      {resizeHandles}
    </div>
  );
}

const VideoMeetingForExport =
  VideoMeeting as unknown as ElementComponent<VideoMeetingElementData>;

VideoMeetingForExport.elementName = "Video Meeting";
VideoMeetingForExport.description = "Host a video meeting in your presentation";
VideoMeetingForExport.icon = "videocam";
VideoMeetingForExport.blankFactory = (newId, newZ, data) => ({
  type: ElementTypeName.VideoMeeting,
  name: "New Video Meeting",

  id: newId,
  x: data.metadata.width / 2 - 150,
  y: data.metadata.height / 2 - 50,
  z: newZ,

  isLocked: false,
  width: 300,
  height: 100,

  sessionName: "",
  sessionPassword: Math.floor(Math.random() * 8999 + 1000).toString(),

  visible: {
    default: ShowHideDefaultVisibility.Show,
    except: [],
  },
});
VideoMeetingForExport.clone = (source, newId, newName, newZ) => ({
  type: ElementTypeName.VideoMeeting,
  name: newName,

  id: newId,
  x: source.x,
  y: source.y,
  z: newZ,

  isLocked: source.isLocked,
  width: source.width,
  height: source.height,

  sessionName: source.sessionName,
  sessionPassword: source.sessionPassword,

  visible: source.visible,
});

export default VideoMeetingForExport;
