import type { ComputedRef, Ref } from 'vue';

import type { ProductCategoryManageDto } from '#/api/product';
import type {
  CategoryFormModel,
  DrawerMode,
} from '#/views/product/category/types';

/**
 * 文件职责：分类编辑抽屉动作。
 * 1. 管理新增/编辑抽屉与表单状态。
 * 2. 提交保存与删除分类操作。
 */
import { message, Modal } from 'ant-design-vue';

import {
  deleteProductCategoryApi,
  saveProductCategoryApi,
} from '#/api/product';
import { CATEGORY_CHANNEL_ORDER } from '#/views/product/category/types';

import { normalizeCategoryChannels } from './constants';

interface CreateDrawerActionsOptions {
  categories: Ref<ProductCategoryManageDto[]>;
  drawerMode: Ref<DrawerMode>;
  form: CategoryFormModel;
  isDrawerOpen: Ref<boolean>;
  isDrawerSubmitting: Ref<boolean>;
  loadCategories: (preferredCategoryId?: string) => Promise<void>;
  selectedCategory: ComputedRef<ProductCategoryManageDto | undefined>;
  selectedStoreId: Ref<string>;
}

export function createDrawerActions(options: CreateDrawerActionsOptions) {
  function resetDrawerForm() {
    options.form.id = '';
    options.form.name = '';
    options.form.description = '';
    options.form.icon = '';
    options.form.channels = [...CATEGORY_CHANNEL_ORDER];
    options.form.sort = options.categories.value.length + 1;
    options.form.status = 'enabled';
  }

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

  function setFormDescription(value: string) {
    options.form.description = value;
  }

  function setFormIcon(value: string) {
    options.form.icon = value;
  }

  function setFormSort(value: number) {
    options.form.sort =
      Number.isFinite(value) && value > 0 ? Math.floor(value) : 1;
  }

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

  function openEditDrawer() {
    const current = options.selectedCategory.value;
    if (!current) {
      message.warning('请先选择分类');
      return;
    }
    options.drawerMode.value = 'edit';
    options.form.id = current.id;
    options.form.name = current.name;
    options.form.description = current.description;
    options.form.icon = current.icon;
    options.form.channels = normalizeCategoryChannels(current.channels);
    options.form.sort = current.sort;
    options.form.status = current.status;
    options.isDrawerOpen.value = true;
  }

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

  function toggleDrawerChannel(channel: CategoryFormModel['channels'][number]) {
    if (options.form.channels.includes(channel)) {
      options.form.channels = options.form.channels.filter(
        (item) => item !== channel,
      );
      return;
    }
    options.form.channels = [...options.form.channels, channel];
  }

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

  async function submitDrawer() {
    if (!options.selectedStoreId.value) return;
    if (!options.form.name.trim()) {
      message.warning('请输入分类名称');
      return;
    }
    if (options.form.channels.length === 0) {
      message.warning('请至少选择一个销售渠道');
      return;
    }

    options.isDrawerSubmitting.value = true;
    try {
      const result = await saveProductCategoryApi({
        storeId: options.selectedStoreId.value,
        id: options.form.id || undefined,
        name: options.form.name.trim(),
        description: options.form.description.trim(),
        icon: options.form.icon.trim() || 'lucide:folder',
        channels: [...options.form.channels],
        sort: options.form.sort,
        status: options.form.status,
      });
      message.success(
        options.drawerMode.value === 'create' ? '分类添加成功' : '保存成功',
      );
      options.isDrawerOpen.value = false;
      await options.loadCategories(result.id);
    } catch (error) {
      console.error(error);
    } finally {
      options.isDrawerSubmitting.value = false;
    }
  }

  function removeSelectedCategory() {
    const current = options.selectedCategory.value;
    if (!options.selectedStoreId.value || !current) return;

    Modal.confirm({
      title: `确认删除分类「${current.name}」吗？`,
      content: '若分类下还有商品会删除失败。',
      okText: '确认删除',
      cancelText: '取消',
      async onOk() {
        await deleteProductCategoryApi({
          storeId: options.selectedStoreId.value,
          categoryId: current.id,
        });
        message.success('分类已删除');
        await options.loadCategories();
      },
    });
  }

  return {
    openCreateDrawer,
    openEditDrawer,
    removeSelectedCategory,
    setDrawerOpen,
    setFormDescription,
    setFormIcon,
    setFormName,
    setFormSort,
    submitDrawer,
    toggleDrawerChannel,
    toggleDrawerStatus,
  };
}
