<script setup lang="ts">
import { onMounted, onUnmounted, ref, useTemplateRef, watch } from 'vue';

import { useViewVisible } from '@/hooks/view-visible';
import { envAreaEditorPageUrl, EnvAreaMsgType, getEnvAreaMsgType } from '@/utils/env-area';

import type { IframeMsg, RegionsPointsItem } from '@/types';

interface Props {
  areaData?: RegionsPointsItem;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  openOutdoorDrawer: [];
  saveAreaCanvas: [canvas: string];
}>();

const { visible, showView, hideView } = useViewVisible();
const iframeRef = useTemplateRef('editorIframe');
const isIframeLoaded = ref(false);

onMounted(() => {
  window.addEventListener('message', handleIframeMsg);
});

onUnmounted(() => {
  window.removeEventListener('message', handleIframeMsg);
});

watch(visible, () => {
  if (visible.value && isIframeLoaded.value) {
    sendAreaData();
  }
});

const handleIframeMsg = (e: MessageEvent<IframeMsg>) => {
  const { msgType } = e.data;

  if (msgType === getEnvAreaMsgType(EnvAreaMsgType.EditLoaded)) {
    isIframeLoaded.value = true;
    sendAreaData();
  } else if (msgType === getEnvAreaMsgType(EnvAreaMsgType.EditOutdoorTempHumidity)) {
    emit('openOutdoorDrawer');
  } else if (msgType === getEnvAreaMsgType(EnvAreaMsgType.SubmitEditArea)) {
    emit('saveAreaCanvas', e.data.canvas);
  } else if (msgType === getEnvAreaMsgType(EnvAreaMsgType.CancelEditArea)) {
    hideView();
  }
};

const sendAreaData = () => {
  if (props.areaData) {
    const msg: IframeMsg = {
      msgType: getEnvAreaMsgType(EnvAreaMsgType.EditArea),
      ...JSON.parse(JSON.stringify(props.areaData)),
    };

    iframeRef.value?.contentWindow?.postMessage(msg, '*');
  }
};

defineExpose({
  showView,
  hideView,
});
</script>

<template>
  <AModal
    v-model:open="visible"
    wrap-class-name="env-area-editor-modal"
    width="100%"
    centered
    :closable="false"
    :mask-closable="false"
    :footer="null"
  >
    <iframe ref="editorIframe" :src="envAreaEditorPageUrl"></iframe>
    <ASpin v-if="!isIframeLoaded" class="center-loading env-area-editor-loading" :spinning="true" />
  </AModal>
</template>

<style lang="scss">
.env-area-editor-modal {
  padding: 32px;

  .ant-modal {
    max-width: 1147px;
  }

  .ant-modal,
  .ant-modal > div,
  .ant-modal-content {
    height: 812px;
  }

  .ant-modal-content {
    padding: 0;
  }

  .ant-modal-body,
  iframe {
    width: 100%;
    height: 100%;
  }

  iframe {
    overflow: hidden;
    background: transparent;
    border: none;
    border-radius: 8px;
  }

  .env-area-editor-loading {
    background-color: #fff;
    border-radius: 8px;
  }
}
</style>
