import type { CostDeleteModalState, CostDetailDrawerState } from '../../types';

/**
 * 文件职责：成本明细抽屉与删除弹窗动作。
 */
import type {
  FinanceCostCategoryCode,
  FinanceCostEntryDetailDto,
} from '#/api/finance/cost';

interface DrawerActionOptions {
  deleteModalState: CostDeleteModalState;
  drawerState: CostDetailDrawerState;
  removeDetailItem: (
    category: FinanceCostCategoryCode,
    itemId: string | undefined,
  ) => void;
  upsertDetailItem: (
    category: FinanceCostCategoryCode,
    detail: FinanceCostEntryDetailDto,
    mode: 'create' | 'edit',
  ) => void;
}

/** 创建抽屉与弹窗动作。 */
export function createDrawerActions(options: DrawerActionOptions) {
  function openCreateDrawer(category: FinanceCostCategoryCode) {
    options.drawerState.open = true;
    options.drawerState.mode = 'create';
    options.drawerState.category = category;
    options.drawerState.sourceItem = undefined;
  }

  function openEditDrawer(
    category: FinanceCostCategoryCode,
    item: FinanceCostEntryDetailDto,
  ) {
    options.drawerState.open = true;
    options.drawerState.mode = 'edit';
    options.drawerState.category = category;
    options.drawerState.sourceItem = { ...item };
  }

  function closeDrawer() {
    options.drawerState.open = false;
    options.drawerState.sourceItem = undefined;
  }

  function submitDrawer(detail: FinanceCostEntryDetailDto) {
    options.upsertDetailItem(
      options.drawerState.category,
      detail,
      options.drawerState.mode,
    );
    closeDrawer();
  }

  function openDeleteModal(
    category: FinanceCostCategoryCode,
    item: FinanceCostEntryDetailDto,
  ) {
    options.deleteModalState.open = true;
    options.deleteModalState.category = category;
    options.deleteModalState.item = item;
  }

  function closeDeleteModal() {
    options.deleteModalState.open = false;
    options.deleteModalState.item = undefined;
  }

  function confirmDelete() {
    options.removeDetailItem(
      options.deleteModalState.category,
      options.deleteModalState.item?.itemId,
    );
    closeDeleteModal();
  }

  return {
    closeDeleteModal,
    closeDrawer,
    confirmDelete,
    openCreateDrawer,
    openDeleteModal,
    openEditDrawer,
    submitDrawer,
  };
}
