import type { Ref } from 'vue';

/**
 * 文件职责：堂食区域动作。
 * 1. 管理区域新增/编辑抽屉状态与字段。
 * 2. 处理区域新增、编辑、删除流程。
 */
import type { DineInAreaDto, DineInTableDto } from '#/api/store-dinein';
import type {
  DineInAreaDrawerMode,
  DineInAreaFormState,
} from '#/views/store/dine-in/types';

import { message } from 'ant-design-vue';

import { deleteDineInAreaApi, saveDineInAreaApi } from '#/api/store-dinein';

import { countAreaTables, sortAreas, validateAreaForm } from './helpers';

interface CreateAreaActionsOptions {
  areaDrawerMode: Ref<DineInAreaDrawerMode>;
  areaForm: DineInAreaFormState;
  areas: Ref<DineInAreaDto[]>;
  fixSelectedArea: () => void;
  isAreaDrawerOpen: Ref<boolean>;
  isSavingArea: Ref<boolean>;
  selectedAreaId: Ref<string>;
  selectedStoreId: Ref<string>;
  tables: Ref<DineInTableDto[]>;
  updateSnapshot: () => void;
}

export function createAreaActions(options: CreateAreaActionsOptions) {
  /** 打开区域抽屉并初始化表单。 */
  function openAreaDrawer(mode: DineInAreaDrawerMode, area?: DineInAreaDto) {
    options.areaDrawerMode.value = mode;
    if (mode === 'edit' && area) {
      options.areaForm.id = area.id;
      options.areaForm.name = area.name;
      options.areaForm.description = area.description;
      options.areaForm.sort = area.sort;
      options.isAreaDrawerOpen.value = true;
      return;
    }

    const nextSort =
      options.areas.value.length === 0
        ? 1
        : Math.max(...options.areas.value.map((item) => item.sort)) + 1;
    options.areaForm.id = '';
    options.areaForm.name = '';
    options.areaForm.description = '';
    options.areaForm.sort = nextSort;
    options.isAreaDrawerOpen.value = true;
  }

  /** 控制区域抽屉显隐。 */
  function setAreaDrawerOpen(value: boolean) {
    options.isAreaDrawerOpen.value = value;
  }

  function setAreaName(value: string) {
    options.areaForm.name = value;
  }

  function setAreaDescription(value: string) {
    options.areaForm.description = value;
  }

  function setAreaSort(value: number) {
    options.areaForm.sort = Math.max(1, Math.floor(Number(value || 1)));
  }

  /** 提交区域表单。 */
  async function handleSubmitArea() {
    const validateMessage = validateAreaForm({
      areaId: options.areaForm.id,
      areas: options.areas.value,
      form: options.areaForm,
    });
    if (validateMessage) {
      message.error(validateMessage);
      return;
    }
    if (!options.selectedStoreId.value) return;

    options.isSavingArea.value = true;
    try {
      const savedArea = await saveDineInAreaApi({
        storeId: options.selectedStoreId.value,
        area: {
          id: options.areaForm.id || undefined,
          name: options.areaForm.name.trim(),
          description: options.areaForm.description.trim(),
          sort: Math.max(1, Math.floor(options.areaForm.sort)),
        },
      });

      options.areas.value =
        options.areaDrawerMode.value === 'edit' && options.areaForm.id
          ? sortAreas(
              options.areas.value.map((item) =>
                item.id === options.areaForm.id ? savedArea : item,
              ),
            )
          : sortAreas([...options.areas.value, savedArea]);

      if (!options.selectedAreaId.value) {
        options.selectedAreaId.value = savedArea.id;
      }
      options.fixSelectedArea();
      options.updateSnapshot();
      options.isAreaDrawerOpen.value = false;
      message.success(
        options.areaDrawerMode.value === 'edit' ? '区域已保存' : '区域已添加',
      );
    } catch (error) {
      console.error(error);
    } finally {
      options.isSavingArea.value = false;
    }
  }

  /** 删除区域。 */
  async function handleDeleteArea(area: DineInAreaDto) {
    if (!options.selectedStoreId.value) return;

    const tableCount = countAreaTables(area.id, options.tables.value);
    if (tableCount > 0) {
      message.error('该区域仍有桌位，请先迁移或删除桌位');
      return;
    }

    options.isSavingArea.value = true;
    try {
      await deleteDineInAreaApi({
        storeId: options.selectedStoreId.value,
        areaId: area.id,
      });
      options.areas.value = options.areas.value.filter(
        (item) => item.id !== area.id,
      );
      options.fixSelectedArea();
      options.updateSnapshot();
      message.success('区域已删除');
    } catch (error) {
      console.error(error);
    } finally {
      options.isSavingArea.value = false;
    }
  }

  return {
    handleDeleteArea,
    handleSubmitArea,
    openAreaDrawer,
    setAreaDescription,
    setAreaDrawerOpen,
    setAreaName,
    setAreaSort,
  };
}
