import type { Ref } from 'vue';

import type { SaveProductLabelDto } from '#/api/product';
import type {
  LabelEditorForm,
  ProductLabelTableRowViewModel,
} from '#/views/product/labels/types';

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

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

import { createDefaultLabelForm, normalizeLabelColor } from './constants';

interface CreateDrawerActionsOptions {
  drawerMode: Ref<'create' | 'edit'>;
  editingLabelId: Ref<string>;
  form: LabelEditorForm;
  isDrawerOpen: Ref<boolean>;
  isDrawerSubmitting: Ref<boolean>;
  loadLabels: () => Promise<void>;
  rows: Ref<ProductLabelTableRowViewModel[]>;
  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 setFormColor(value: string) {
    options.form.color = normalizeLabelColor(value);
  }

  function setFormSort(value: number) {
    options.form.sort = Number.isNaN(value)
      ? 0
      : Math.max(0, Math.floor(value));
  }

  function toggleFormStatus() {
    options.form.status =
      options.form.status === 'enabled' ? 'disabled' : 'enabled';
  }

  function resetForm() {
    const next = createDefaultLabelForm(options.rows.value.length + 1);
    options.editingLabelId.value = '';
    options.form.name = next.name;
    options.form.color = next.color;
    options.form.sort = next.sort;
    options.form.status = next.status;
  }

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

  function openEditDrawer(item: ProductLabelTableRowViewModel) {
    options.drawerMode.value = 'edit';
    options.editingLabelId.value = item.id;
    options.form.name = item.name;
    options.form.color = normalizeLabelColor(item.color);
    options.form.sort = item.sort;
    options.form.status = item.status;
    options.isDrawerOpen.value = true;
  }

  function buildSavePayload(): SaveProductLabelDto {
    return {
      storeId: options.selectedStoreId.value,
      id: options.editingLabelId.value || undefined,
      name: options.form.name.trim(),
      color: normalizeLabelColor(options.form.color),
      sort: options.form.sort,
      status: options.form.status,
    };
  }

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

    options.isDrawerSubmitting.value = true;
    try {
      await saveProductLabelApi(buildSavePayload());
      message.success(
        options.drawerMode.value === 'create' ? '标签已创建' : '标签已更新',
      );
      options.isDrawerOpen.value = false;
      await options.loadLabels();
    } catch (error) {
      console.error(error);
    } finally {
      options.isDrawerSubmitting.value = false;
    }
  }

  return {
    openCreateDrawer,
    openEditDrawer,
    setDrawerOpen,
    setFormColor,
    setFormName,
    setFormSort,
    submitDrawer,
    toggleFormStatus,
  };
}
