import type { Ref } from 'vue';

import type { ProductSpecDto, SaveProductSpecDto } from '#/api/product';
import type {
  ProductSpecCardViewModel,
  SpecEditorForm,
} from '#/views/product/specs/types';

/**
 * 文件职责：规格做法编辑抽屉动作。
 * 1. 管理模板新增/编辑抽屉与表单状态。
 * 2. 处理表单校验与保存提交。
 */
import { message } from 'ant-design-vue';

import { saveProductSpecApi } from '#/api/product';

import { createDefaultOption } from './constants';

interface CreateDrawerActionsOptions {
  drawerMode: Ref<'create' | 'edit'>;
  form: SpecEditorForm;
  isDrawerOpen: Ref<boolean>;
  isDrawerSubmitting: Ref<boolean>;
  loadSpecs: () => Promise<void>;
  rows: Ref<ProductSpecCardViewModel[]>;
  selectedStoreId: Ref<string>;
}

export function createDrawerActions(options: CreateDrawerActionsOptions) {
  function setDrawerOpen(value: boolean) {
    options.isDrawerOpen.value = value;
  }

  function setFormName(value: string) {
    options.form.name = value;
  }

  function setFormType(value: SpecEditorForm['type']) {
    options.form.type = value;
  }

  function setFormSelectionType(value: SpecEditorForm['selectionType']) {
    options.form.selectionType = value;
  }

  function setFormIsRequired(value: boolean) {
    options.form.isRequired = value;
  }

  function setOptionName(index: number, value: string) {
    const current = options.form.values[index];
    if (!current) return;
    current.name = value;
  }

  function setOptionExtraPrice(index: number, value: null | number) {
    const current = options.form.values[index];
    if (!current) return;
    current.extraPrice = Number(value ?? 0);
  }

  function addOption() {
    options.form.values.push(
      createDefaultOption(options.form.values.length + 1),
    );
  }

  function removeOption(index: number) {
    if (options.form.values.length <= 1) {
      message.warning('至少保留一个选项');
      return;
    }
    options.form.values.splice(index, 1);
    options.form.values.forEach((item, idx) => {
      item.sort = idx + 1;
    });
  }

  function resetForm() {
    options.form.id = '';
    options.form.name = '';
    options.form.type = 'spec';
    options.form.selectionType = 'single';
    options.form.isRequired = true;
    options.form.sort = options.rows.value.length + 1;
    options.form.status = 'enabled';
    options.form.productIds = [];
    options.form.values = [createDefaultOption()];
  }

  function openCreateDrawer() {
    options.drawerMode.value = 'create';
    resetForm();
    options.isDrawerOpen.value = true;
  }

  function openEditDrawer(item: ProductSpecDto) {
    options.drawerMode.value = 'edit';
    options.form.id = item.id;
    options.form.name = item.name;
    options.form.type = item.type;
    options.form.selectionType = item.selectionType;
    options.form.isRequired = item.isRequired;
    options.form.sort = item.sort;
    options.form.status = item.status;
    options.form.productIds = [...item.productIds];
    options.form.values = item.values.map((value, index) => ({
      id: value.id,
      name: value.name,
      extraPrice: value.extraPrice,
      sort: value.sort || index + 1,
    }));
    if (options.form.values.length === 0) {
      options.form.values = [createDefaultOption()];
    }
    options.isDrawerOpen.value = true;
  }

  function normalizeSubmitValues() {
    return options.form.values
      .map((item, index) => ({
        ...item,
        name: item.name.trim(),
        sort: index + 1,
      }))
      .filter((item) => item.name);
  }

  function buildSavePayload(
    values: SpecEditorForm['values'],
  ): SaveProductSpecDto {
    return {
      storeId: options.selectedStoreId.value,
      id: options.form.id || undefined,
      name: options.form.name.trim(),
      type: options.form.type,
      selectionType: options.form.selectionType,
      isRequired: options.form.isRequired,
      sort: options.form.sort,
      status: options.form.status,
      productIds: [...options.form.productIds],
      values: values.map((item) => ({
        id: item.id || undefined,
        name: item.name,
        extraPrice: item.extraPrice,
        sort: item.sort,
      })),
    };
  }

  async function submitDrawer() {
    if (!options.selectedStoreId.value) return;
    if (!options.form.name.trim()) {
      message.warning('请输入模板名称');
      return;
    }

    const normalizedValues = normalizeSubmitValues();
    if (normalizedValues.length === 0) {
      message.warning('请至少添加一个选项');
      return;
    }

    const uniqueNames = new Set(
      normalizedValues.map((item) => item.name.toLowerCase()),
    );
    if (uniqueNames.size !== normalizedValues.length) {
      message.warning('选项名称不能重复');
      return;
    }

    options.isDrawerSubmitting.value = true;
    try {
      await saveProductSpecApi(buildSavePayload(normalizedValues));
      message.success(
        options.drawerMode.value === 'create' ? '模板已添加' : '模板已保存',
      );
      options.isDrawerOpen.value = false;
      await options.loadSpecs();
    } catch (error) {
      console.error(error);
    } finally {
      options.isDrawerSubmitting.value = false;
    }
  }

  return {
    addOption,
    openCreateDrawer,
    openEditDrawer,
    removeOption,
    setDrawerOpen,
    setFormIsRequired,
    setFormName,
    setFormSelectionType,
    setFormType,
    setOptionExtraPrice,
    setOptionName,
    submitDrawer,
  };
}
