<script setup lang="ts">
import { computed } from 'vue';
import { $t } from '@/locales';

defineOptions({
  name: 'BusinessFormDrawer',
  inheritAttrs: false
});

type DrawerPreset = 'md' | 'lg' | 'xl';

interface Props {
  title: string;
  preset?: DrawerPreset;
  size?: string | number;
  loading?: boolean;
  confirmLoading?: boolean;
  confirmDisabled?: boolean;
  showFooter?: boolean;
  scrollbar?: boolean;
  bodyHeight?: string | number;
  cancelText?: string;
  confirmText?: string;
}

interface Emits {
  (e: 'cancel'): void;
  (e: 'confirm'): void;
}

const props = withDefaults(defineProps<Props>(), {
  preset: 'lg',
  size: undefined,
  loading: false,
  confirmLoading: false,
  confirmDisabled: false,
  showFooter: true,
  scrollbar: true,
  bodyHeight: '100%',
  cancelText: '',
  confirmText: ''
});

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>({
  default: false
});

const DRAWER_SIZE_MAP: Record<DrawerPreset, string> = {
  md: '480px',
  lg: '720px',
  xl: '960px'
};

const drawerSize = computed(() => props.size ?? DRAWER_SIZE_MAP[props.preset]);

const resolvedCancelText = computed(() => props.cancelText || $t('common.cancel'));
const resolvedConfirmText = computed(() => props.confirmText || $t('common.confirm'));

function handleCancel() {
  visible.value = false;
  emit('cancel');
}

function handleConfirm() {
  emit('confirm');
}
</script>

<template>
  <ElDrawer
    v-model="visible"
    class="business-form-drawer"
    :title="props.title"
    :size="drawerSize"
    :close-on-click-modal="false"
    destroy-on-close
    header-class="business-form-drawer__header"
    body-class="business-form-drawer__body"
    footer-class="business-form-drawer__footer"
    v-bind="$attrs"
  >
    <ElScrollbar
      v-if="props.scrollbar"
      :height="props.bodyHeight"
      class="business-form-drawer__scrollbar"
      view-class="business-form-drawer__scrollbar-view"
    >
      <div v-loading="props.loading" class="business-form-drawer__content">
        <slot />
      </div>
    </ElScrollbar>

    <div v-else v-loading="props.loading" class="business-form-drawer__content">
      <slot />
    </div>

    <template v-if="props.showFooter" #footer>
      <slot name="footer" :close="handleCancel">
        <ElSpace :size="16">
          <ElButton @click="handleCancel">{{ resolvedCancelText }}</ElButton>
          <ElButton
            type="primary"
            :loading="props.confirmLoading"
            :disabled="props.confirmDisabled"
            @click="handleConfirm"
          >
            {{ resolvedConfirmText }}
          </ElButton>
        </ElSpace>
      </slot>
    </template>
  </ElDrawer>
</template>

<style scoped></style>
