<script lang="ts" setup>
import type { AssetVehicleReplacementApi } from '#/api/asset/vehicle-replacement';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Card, message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  createVehicleReplacement,
  getVehicleReplacement,
  updateVehicleReplacement,
} from '#/api/asset/vehicle-replacement';
import { $t } from '#/locales';

import { useFormSchema } from '../data';

type FormMode = 'create' | 'edit' | 'view';

const emit = defineEmits(['success']);
const formData = ref<AssetVehicleReplacementApi.VehicleReplacement>();
const mode = ref<FormMode>('create');

const isReadOnly = computed(() => mode.value === 'view');

const getTitle = computed(() => {
  if (mode.value === 'view') {
    return '查看替换车';
  }
  return formData.value?.id
    ? $t('ui.actionTitle.edit', ['替换车'])
    : $t('ui.actionTitle.create', ['替换车']);
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 150,
  },
  layout: 'horizontal',
  schema: useFormSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    if (isReadOnly.value) {
      await modalApi.close();
      return;
    }

    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }

    modalApi.lock();

    const data =
      (await formApi.getValues()) as AssetVehicleReplacementApi.VehicleReplacement;

    try {
      await (formData.value?.id
        ? updateVehicleReplacement(data)
        : createVehicleReplacement(data));
      await modalApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      mode.value = 'create';
      return;
    }

    const data = modalApi.getData<
      AssetVehicleReplacementApi.VehicleReplacement & { _mode?: FormMode }
    >();

    // Determine mode
    if (data?._mode) {
      mode.value = data._mode;
    } else if (data?.id) {
      mode.value = 'edit';
    } else {
      mode.value = 'create';
    }

    // Set readonly state on form
    await formApi.setState({ commonConfig: { componentProps: { disabled: isReadOnly.value } } });

    if (data?.id) {
      // Edit or view mode: load data from API
      modalApi.lock();
      try {
        formData.value = await getVehicleReplacement(data.id);
        await formApi.setValues(formData.value);
      } finally {
        modalApi.unlock();
      }
    } else if (data) {
      // Create mode: check for pre-fill data (contractId, vehicleId, deliveryOrderId)
      const prefillData: Record<string, any> = {};
      if (data.contractId) {
        prefillData.contractId = data.contractId;
      }
      if (data.originalVehicleId) {
        prefillData.originalVehicleId = data.originalVehicleId;
      }
      if (data.deliveryOrderId) {
        prefillData.deliveryOrderId = data.deliveryOrderId;
      }
      if (Object.keys(prefillData).length > 0) {
        await formApi.setValues(prefillData);
      }
    }
  },
});
</script>

<template>
  <Modal :title="getTitle" class="w-3/4">
    <div class="mx-4">
      <Card :bordered="false">
        <Form />
      </Card>
    </div>
  </Modal>
</template>
