<script lang="ts" setup>
import type { PageBasicInfo } from './PageBasicInfoEditor.vue';
import type { PagePublishInfo } from './PagePublishInfoEditor.vue';

import { computed, ref, watch } from 'vue';

import { $t } from '@vben/locales';

import { ElButton, ElInput, ElMessage, ElStep, ElSteps } from 'element-plus';

import PageBasicInfoEditor from './PageBasicInfoEditor.vue';
import PagePublishInfoEditor from './PagePublishInfoEditor.vue';

export interface PageEditorData {
  basicForm: PageBasicInfo;
  pageConfig: Record<string, any>;
  publishData?: PagePublishInfo;
}

const props = withDefaults(
  defineProps<{
    initialBasicForm?: PageBasicInfo;
    initialPageConfig?: Record<string, any>;
    initialPublishData?: PagePublishInfo;
    isEditMode?: boolean;
    readonly?: boolean;
    showActions?: boolean;
    showSteps?: boolean;
    step?: number;
    workflowMode?: boolean;
  }>(),
  {
    initialBasicForm: undefined,
    initialPageConfig: undefined,
    initialPublishData: undefined,
    isEditMode: false,
    readonly: false,
    showActions: true,
    showSteps: true,
    step: undefined,
    workflowMode: false,
  },
);

const emit = defineEmits<{
  cancel: [];
  save: [data: PageEditorData];
  'step-change': [step: number];
  'update:step': [step: number];
}>();

const internalStep = ref(0);
const currentStep = computed({
  get: () => (props.step === undefined ? internalStep.value : props.step),
  set: (val) => {
    if (props.step === undefined) internalStep.value = val;
    else emit('update:step', val);
    emit('step-change', val);
  },
});

const basicForm = ref<PageBasicInfo>({
  category: 'dashboard',
  code: '',
  description: '',
  name: '',
  sort: 0,
});

const pageConfigText = ref('{}');
const publishData = ref<PagePublishInfo>({
  menu_icon: 'lucide:layout-dashboard',
  menu_name: '',
  menu_order: 0,
  menu_parent_id: undefined,
});

const steps = computed(() => {
  const base = [
    { title: $t('page-manager.editor.steps.basic') || '基础信息' },
    { title: $t('page-manager.editor.steps.design') || '页面设计' },
  ];
  if (props.workflowMode) {
    base.push({ title: $t('page-manager.editor.steps.publish') || '发布配置' });
  }
  return base;
});

const canGoPrev = computed(() => currentStep.value > 0);
const isLastStep = computed(() => currentStep.value === steps.value.length - 1);

watch(
  () => props.initialBasicForm,
  (val) => {
    if (val) basicForm.value = { ...val };
  },
  { immediate: true },
);

watch(
  () => props.initialPageConfig,
  (val) => {
    if (val) pageConfigText.value = JSON.stringify(val, null, 2);
  },
  { immediate: true },
);

watch(
  () => props.initialPublishData,
  (val) => {
    if (val) publishData.value = { ...val };
  },
  { immediate: true },
);

watch(
  () => basicForm.value.name,
  (name) => {
    if (props.workflowMode && name && !publishData.value.menu_name) {
      publishData.value.menu_name = name;
    }
  },
);

function getData(): PageEditorData {
  const pageConfig = pageConfigText.value.trim()
    ? JSON.parse(pageConfigText.value)
    : {};
  return {
    basicForm: { ...basicForm.value },
    pageConfig,
    publishData: props.workflowMode ? { ...publishData.value } : undefined,
  };
}

function setData(data: Partial<PageEditorData>) {
  if (data.basicForm) basicForm.value = { ...data.basicForm };
  if (data.pageConfig) pageConfigText.value = JSON.stringify(data.pageConfig, null, 2);
  if (data.publishData) publishData.value = { ...publishData.value, ...data.publishData };
}

function handlePrev() {
  if (canGoPrev.value) currentStep.value -= 1;
}

function handleNext() {
  if (!isLastStep.value) currentStep.value += 1;
}

function handleSave() {
  try {
    emit('save', getData());
  } catch {
    ElMessage.error('页面配置不是有效 JSON');
  }
}

defineExpose({ getData, setData });
</script>

<template>
  <div class="flex h-full min-h-0 flex-col">
    <div v-if="showSteps" class="border-border border-b px-6 py-4">
      <ElSteps :active="currentStep" align-center finish-status="success">
        <ElStep v-for="item in steps" :key="item.title" :title="item.title" />
      </ElSteps>
    </div>

    <div class="min-h-0 flex-1 overflow-auto p-6">
      <PageBasicInfoEditor
        v-if="currentStep === 0"
        v-model="basicForm"
        :is-edit-mode="isEditMode"
      />
      <div v-else-if="currentStep === 1" class="h-full min-h-[460px]">
        <div class="mb-3 text-sm text-muted-foreground">
          确认 AI 生成的页面配置，保存后将作为仪表盘发布和菜单挂载的数据基础。
        </div>
        <ElInput
          v-model="pageConfigText"
          :readonly="readonly"
          class="h-full"
          resize="none"
          type="textarea"
          placeholder="页面配置 JSON"
        />
      </div>
      <PagePublishInfoEditor
        v-else
        v-model="publishData"
        :page-code="basicForm.code"
      />
    </div>

    <div v-if="showActions" class="border-border flex justify-end gap-2 border-t px-6 py-4">
      <ElButton @click="emit('cancel')">{{ $t('common.cancel') }}</ElButton>
      <ElButton :disabled="!canGoPrev" @click="handlePrev">上一步</ElButton>
      <ElButton v-if="!isLastStep" type="primary" @click="handleNext">下一步</ElButton>
      <ElButton v-else type="primary" @click="handleSave">{{ $t('common.save') }}</ElButton>
    </div>
  </div>
</template>

<style scoped>
:deep(.el-textarea),
:deep(.el-textarea__inner) {
  height: 100%;
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}
</style>
