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

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

import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElMessage,
  ElOption,
  ElSelect,
  ElSteps,
  ElStep,
} from 'element-plus';

import PublishInfoEditor, { type FormPublishInput } from './PublishInfoEditor.vue';

export interface BasicFormData {
  code: string;
  description: string;
  form_type: 'normal' | 'workflow';
  name: string;
  sort: number;
}

export interface TableConfig {
  alias?: string;
  fields?: any[];
  id?: string;
  meta?: Record<string, any>;
  tableName?: string;
  type?: string;
}

export interface FormEditorData {
  basicForm: BasicFormData;
  formConfig: {
    disabled: boolean;
    formBackground: boolean;
    formBorder: boolean;
    formBorderRadius: number;
    formMargin: number;
    formMaxWidth: number;
    formPadding: number;
    formShadow: boolean;
    formWidth: string;
    items: any[];
    itemSpacing: number;
    labelPosition: 'left' | 'right' | 'top';
    labelWidth: number;
    lifecycleHooks?: any[];
    size: 'default' | 'large' | 'small';
    tableConfigs: TableConfig[];
  };
  formFields: any[];
  listConfig: Record<string, any>;
  publishData?: FormPublishInput;
  tableConfigs: TableConfig[];
}

const props = withDefaults(
  defineProps<{
    initialBasicForm?: BasicFormData;
    initialListDesign?: Record<string, any>;
    initialTableConfigs?: TableConfig[];
    readonly?: boolean;
    showActions?: boolean;
    showSteps?: boolean;
    step?: number;
    workflowMode?: boolean;
  }>(),
  {
    initialBasicForm: undefined,
    initialListDesign: undefined,
    initialTableConfigs: undefined,
    readonly: false,
    showActions: true,
    showSteps: true,
    step: undefined,
    workflowMode: false,
  },
);

const emit = defineEmits<{
  cancel: [];
  save: [data: FormEditorData];
  '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<BasicFormData>({
  code: '',
  description: '',
  form_type: 'normal',
  name: '',
  sort: 0,
});
const tableConfigs = ref<TableConfig[]>([]);
const formConfigText = ref('{}');
const listConfigText = ref('{}');
const formFields = ref<any[]>([]);
const publishData = ref<FormPublishInput>({
  menu_icon: 'lucide:file-text',
  menu_name: '',
  menu_order: 0,
  menu_parent_id: undefined,
});

const steps = computed(() => {
  const base = [
    { title: $t('form-manager.editor.steps.basic') || '基础信息' },
    { title: $t('form-manager.editor.steps.database') || '数据表' },
    { title: $t('form-manager.editor.steps.form') || '表单设计' },
    { title: $t('form-manager.editor.steps.list') || '列表设计' },
  ];
  if (props.workflowMode) {
    base.push({ title: $t('form-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.initialTableConfigs,
  (val) => {
    if (val) tableConfigs.value = [...val];
  },
  { immediate: true },
);

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

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

function parseJson(text: string, fallback: any) {
  if (!text.trim()) return fallback;
  return JSON.parse(text);
}

function buildDefaultFormConfig(items: any[] = []) {
  return {
    disabled: false,
    formBackground: false,
    formBorder: false,
    formBorderRadius: 4,
    formMargin: 0,
    formMaxWidth: 0,
    formPadding: 20,
    formShadow: false,
    formWidth: '100%',
    items,
    itemSpacing: 18,
    labelPosition: 'right' as const,
    labelWidth: 120,
    size: 'default' as const,
    tableConfigs: tableConfigs.value,
  };
}

function getData(): FormEditorData {
  const formConfig = {
    ...buildDefaultFormConfig(),
    ...parseJson(formConfigText.value, {}),
  };
  const listConfig = parseJson(listConfigText.value, {});
  return {
    basicForm: { ...basicForm.value },
    formConfig,
    formFields: [...formFields.value],
    listConfig,
    publishData: props.workflowMode ? { ...publishData.value } : undefined,
    tableConfigs: [...tableConfigs.value],
  };
}

function setData(data: Partial<FormEditorData>) {
  if (data.basicForm) basicForm.value = { ...data.basicForm };
  if (data.tableConfigs) tableConfigs.value = [...data.tableConfigs];
  if (data.formConfig) {
    formConfigText.value = JSON.stringify(data.formConfig, null, 2);
    formFields.value = data.formFields || data.formConfig.items || [];
  }
  if (data.listConfig) listConfigText.value = JSON.stringify(data.listConfig, null, 2);
  if (data.formFields) formFields.value = [...data.formFields];
  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">
      <ElForm v-if="currentStep === 0" :model="basicForm" label-width="100px">
        <ElFormItem label="名称" required>
          <ElInput v-model="basicForm.name" :disabled="readonly" />
        </ElFormItem>
        <ElFormItem label="编码" required>
          <ElInput v-model="basicForm.code" :disabled="readonly" />
        </ElFormItem>
        <ElFormItem label="类型">
          <ElSelect v-model="basicForm.form_type" :disabled="readonly" class="w-full">
            <ElOption label="普通表单" value="normal" />
            <ElOption label="流程表单" value="workflow" />
          </ElSelect>
        </ElFormItem>
        <ElFormItem label="排序">
          <ElInputNumber v-model="basicForm.sort" :disabled="readonly" class="w-full" />
        </ElFormItem>
        <ElFormItem label="描述">
          <ElInput v-model="basicForm.description" :disabled="readonly" type="textarea" />
        </ElFormItem>
      </ElForm>

      <div v-else-if="currentStep === 1" class="space-y-3">
        <div class="text-sm text-muted-foreground">
          确认 AI 生成的数据表结构，保存后将作为后续表单和列表配置的数据基础。
        </div>
        <ElInput
          :model-value="JSON.stringify(tableConfigs, null, 2)"
          readonly
          resize="none"
          type="textarea"
        />
      </div>

      <div v-else-if="currentStep === 2" class="h-full min-h-[420px]">
        <ElInput
          v-model="formConfigText"
          :readonly="readonly"
          class="h-full"
          resize="none"
          type="textarea"
          placeholder="表单配置 JSON"
        />
      </div>

      <div v-else-if="currentStep === 3" class="h-full min-h-[420px]">
        <ElInput
          v-model="listConfigText"
          :readonly="readonly"
          class="h-full"
          resize="none"
          type="textarea"
          placeholder="列表配置 JSON"
        />
      </div>

      <PublishInfoEditor
        v-else
        v-model="publishData"
        :form-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>
