<script setup lang="ts">
import type { DialogContentEmits, DialogContentProps } from 'reka-ui';

import type { CSSProperties } from 'vue';

import type { ClassType } from '@easyflow-core/typings';

import { computed, ref } from 'vue';

import { cn } from '@easyflow-core/shared/utils';

import { X } from 'lucide-vue-next';
import { DialogClose, DialogContent, useForwardPropsEmits } from 'reka-ui';

import DialogOverlay from './DialogOverlay.vue';

const props = withDefaults(
  defineProps<
    DialogContentProps & {
      animationType?: 'scale' | 'slide';
      appendTo?: HTMLElement | string;
      class?: ClassType;
      closeClass?: ClassType;
      closeDisabled?: boolean;
      contentStyle?: CSSProperties;
      modal?: boolean;
      open?: boolean;
      overlayBlur?: number;
      overlayClass?: ClassType;
      overlayStyle?: CSSProperties;
      showClose?: boolean;
      zIndex?: number;
    }
  >(),
  {
    appendTo: 'body',
    animationType: 'scale',
    closeDisabled: false,
    showClose: true,
  },
);
const emits = defineEmits<
  DialogContentEmits & { close: []; closed: []; opened: [] }
>();

const delegatedProps = computed(() => {
  const {
    class: _,
    contentStyle: _contentStyle,
    modal: _modal,
    open: _open,
    overlayClass: _overlayClass,
    overlayStyle: _overlayStyle,
    showClose: __,
    animationType: ___,
    ...delegated
  } = props;

  return delegated;
});

function isAppendToBody() {
  return (
    props.appendTo === 'body' ||
    props.appendTo === document.body ||
    !props.appendTo
  );
}

const position = computed(() => {
  return isAppendToBody() ? 'fixed' : 'absolute';
});

const forwarded = useForwardPropsEmits(delegatedProps, emits);

const contentRef = ref<InstanceType<typeof DialogContent> | null>(null);
function onAnimationEnd(event: AnimationEvent) {
  // 只有在 contentRef 的动画结束时才触发 opened/closed 事件
  if (event.target === contentRef.value?.$el) {
    if (props.open) {
      emits('opened');
    } else {
      emits('closed');
    }
  }
}
defineExpose({
  getContentRef: () => contentRef.value,
});
</script>

<template>
  <Teleport defer :to="appendTo">
    <Transition name="fade">
      <DialogOverlay
        v-if="open && modal"
        :class="props.overlayClass"
        :style="{
          ...(zIndex ? { zIndex } : {}),
          position,
          ...props.overlayStyle,
          backdropFilter:
            overlayBlur && overlayBlur > 0 ? `blur(${overlayBlur}px)` : 'none',
        }"
        @click="() => emits('close')"
      />
    </Transition>
    <DialogContent
      ref="contentRef"
      :style="{
        ...(zIndex ? { zIndex } : {}),
        position,
        ...props.contentStyle,
      }"
      @animationend="onAnimationEnd"
      v-bind="forwarded"
      :class="
        cn(
          'z-popup data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=open]:duration-220 data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 w-full border border-[hsl(var(--glass-border))/0.18] bg-[hsl(var(--glass-tint))/0.84] p-6 shadow-[var(--shadow-float)] outline-none data-[state=closed]:duration-150 data-[state=closed]:ease-in data-[state=open]:ease-out supports-[backdrop-filter]:bg-[hsl(var(--glass-tint))/0.62] sm:rounded-[22px]',
          {
            'data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-4':
              animationType === 'slide',
          },
          props.class,
        )
      "
    >
      <slot></slot>

      <DialogClose
        v-if="showClose"
        :disabled="closeDisabled"
        :class="
          cn(
            'data-[state=open]:text-muted-foreground hover:text-accent-foreground text-foreground/80 flex-center opacity-78 absolute right-3 top-3 h-7 w-7 rounded-full px-1 text-lg shadow-[0_10px_24px_-24px_hsl(var(--foreground)/0.34)] transition-opacity hover:bg-[hsl(var(--surface-contrast-soft))/0.98] hover:opacity-100 focus:outline-none disabled:pointer-events-none data-[state=open]:bg-[hsl(var(--surface-contrast-soft))/0.92]',
            props.closeClass,
          )
        "
        @click="() => emits('close')"
      >
        <X class="h-4 w-4" />
      </DialogClose>
    </DialogContent>
  </Teleport>
</template>
