import type { Ref } from 'vue';

import type {
  ProductAddonGroupDto,
  SaveProductAddonGroupDto,
} from '#/api/product';
import type {
  AddonEditorForm,
  AddonGroupCardViewModel,
} from '#/views/product/addons/types';

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

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

import { createDefaultAddonItem } from './constants';

interface CreateDrawerActionsOptions {
  drawerMode: Ref<'create' | 'edit'>;
  editingGroupId: Ref<string>;
  editingGroupName: Ref<string>;
  editingProductIds: Ref<string[]>;
  form: AddonEditorForm;
  isDrawerOpen: Ref<boolean>;
  isDrawerSubmitting: Ref<boolean>;
  loadAddonGroups: () => Promise<void>;
  rows: Ref<AddonGroupCardViewModel[]>;
  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 setFormDescription(value: string) {
    options.form.description = value;
  }

  function setFormRequired(value: boolean) {
    options.form.required = value;
    if (value && options.form.minSelect < 1) {
      options.form.minSelect = 1;
    }
  }

  function setFormMinSelect(value: number) {
    options.form.minSelect = Math.max(0, value);
    if (options.form.required && options.form.minSelect < 1) {
      options.form.minSelect = 1;
    }
  }

  function setFormMaxSelect(value: number) {
    options.form.maxSelect = Math.max(1, value);
  }

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

  function setItemPrice(index: number, value: number) {
    const current = options.form.items[index];
    if (!current) return;
    current.price = Number.isNaN(value) ? 0 : Math.max(0, value);
  }

  function setItemStock(index: number, value: number) {
    const current = options.form.items[index];
    if (!current) return;
    current.stock = Number.isNaN(value) ? 0 : Math.max(0, Math.floor(value));
  }

  function addItem() {
    options.form.items.push(
      createDefaultAddonItem(options.form.items.length + 1),
    );
  }

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

  function resetForm() {
    options.editingGroupId.value = '';
    options.editingGroupName.value = '';
    options.editingProductIds.value = [];
    options.form.name = '';
    options.form.description = '';
    options.form.required = false;
    options.form.minSelect = 0;
    options.form.maxSelect = 1;
    options.form.sort = options.rows.value.length + 1;
    options.form.status = 'enabled';
    options.form.items = [createDefaultAddonItem()];
  }

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

  function openEditDrawer(item: AddonGroupCardViewModel) {
    options.drawerMode.value = 'edit';
    options.editingGroupId.value = item.id;
    options.editingGroupName.value = item.name;
    options.editingProductIds.value = [...item.productIds];
    options.form.name = item.name;
    options.form.description = item.description;
    options.form.required = item.required;
    options.form.minSelect = item.minSelect;
    options.form.maxSelect = item.maxSelect;
    options.form.sort = item.sort;
    options.form.status = item.status;
    options.form.items = item.items.map((option, index) => ({
      id: option.id,
      name: option.name,
      price: option.price,
      stock: option.stock,
      sort: option.sort || index + 1,
      status: option.status,
    }));
    if (options.form.items.length === 0) {
      options.form.items = [createDefaultAddonItem()];
    }
    options.isDrawerOpen.value = true;
  }

  function normalizeSubmitItems() {
    return options.form.items
      .map((item, index) => ({
        ...item,
        name: item.name.trim(),
        sort: index + 1,
        price: Number(item.price.toFixed(2)),
      }))
      .filter((item) => item.name);
  }

  function buildSavePayload(
    items: ProductAddonGroupDto['items'],
  ): SaveProductAddonGroupDto {
    return {
      storeId: options.selectedStoreId.value,
      id: options.editingGroupId.value || undefined,
      name: options.form.name.trim(),
      description: options.form.description.trim(),
      required: options.form.required,
      minSelect: options.form.minSelect,
      maxSelect: options.form.maxSelect,
      sort: options.form.sort,
      status: options.form.status,
      productIds: [...options.editingProductIds.value],
      items: items.map((item) => ({
        id: item.id || undefined,
        name: item.name,
        price: item.price,
        stock: item.stock,
        sort: item.sort,
        status: item.status,
      })),
    };
  }

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

    const normalizedItems = normalizeSubmitItems();
    if (normalizedItems.length === 0) {
      message.warning('至少保留一个加料项');
      return;
    }

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

    if (options.form.maxSelect < options.form.minSelect) {
      message.warning('最大可选数量不能小于最小可选数量');
      return;
    }

    options.isDrawerSubmitting.value = true;
    try {
      await saveProductAddonGroupApi(buildSavePayload(normalizedItems));
      message.success(
        options.drawerMode.value === 'create' ? '加料组已创建' : '加料组已更新',
      );
      options.isDrawerOpen.value = false;
      await options.loadAddonGroups();
    } catch (error) {
      console.error(error);
    } finally {
      options.isDrawerSubmitting.value = false;
    }
  }

  return {
    addItem,
    openCreateDrawer,
    openEditDrawer,
    removeItem,
    setDrawerOpen,
    setFormDescription,
    setFormMaxSelect,
    setFormMinSelect,
    setFormName,
    setFormRequired,
    setItemName,
    setItemPrice,
    setItemStock,
    submitDrawer,
  };
}
