import type { Ref } from 'vue';

/**
 * 文件职责：堂食桌位动作。
 * 1. 管理桌位抽屉与批量生成弹窗状态。
 * 2. 处理桌位新增、编辑、删除与批量生成流程。
 */
import type {
  DineInAreaDto,
  DineInTableDto,
  DineInTableStatus,
} from '#/api/store-dinein';
import type {
  DineInBatchFormState,
  DineInTableDrawerMode,
  DineInTableFormState,
} from '#/views/store/dine-in/types';

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

import {
  batchCreateDineInTablesApi,
  deleteDineInTableApi,
  saveDineInTableApi,
} from '#/api/store-dinein';

import {
  generateBatchCodes,
  normalizeTableCode,
  sortTables,
  validateBatchForm,
  validateTableForm,
} from './helpers';

interface CreateTableActionsOptions {
  areas: Ref<DineInAreaDto[]>;
  batchForm: DineInBatchFormState;
  isBatchModalOpen: Ref<boolean>;
  isSavingBatch: Ref<boolean>;
  isSavingTable: Ref<boolean>;
  isTableDrawerOpen: Ref<boolean>;
  selectedStoreId: Ref<string>;
  selectedTableAreaId: Ref<string>;
  tableDrawerMode: Ref<DineInTableDrawerMode>;
  tableForm: DineInTableFormState;
  tables: Ref<DineInTableDto[]>;
  updateSnapshot: () => void;
}

export function createTableActions(options: CreateTableActionsOptions) {
  /** 打开桌位抽屉并初始化表单。 */
  function openTableDrawer(
    mode: DineInTableDrawerMode,
    table?: DineInTableDto,
  ) {
    options.tableDrawerMode.value = mode;
    if (mode === 'edit' && table) {
      options.tableForm.id = table.id;
      options.tableForm.code = table.code;
      options.tableForm.areaId = table.areaId;
      options.tableForm.seats = table.seats;
      options.tableForm.tags = [...table.tags];
      options.tableForm.sourceStatus = table.status;
      options.tableForm.isDisabled = table.status === 'disabled';
      options.isTableDrawerOpen.value = true;
      return;
    }

    options.tableForm.id = '';
    options.tableForm.code = '';
    options.tableForm.areaId = options.selectedTableAreaId.value;
    options.tableForm.seats = 4;
    options.tableForm.tags = [];
    options.tableForm.sourceStatus = 'free';
    options.tableForm.isDisabled = false;
    options.isTableDrawerOpen.value = true;
  }

  /** 控制桌位抽屉显隐。 */
  function setTableDrawerOpen(value: boolean) {
    options.isTableDrawerOpen.value = value;
  }

  function setTableCode(value: string) {
    options.tableForm.code = value;
  }

  function setTableAreaId(value: string) {
    options.tableForm.areaId = value;
  }

  function setTableSeats(value: number) {
    options.tableForm.seats = Math.max(1, Math.floor(Number(value || 1)));
  }

  function setTableDisabled(value: boolean) {
    options.tableForm.isDisabled = Boolean(value);
  }

  function setTableTags(tags: string[]) {
    options.tableForm.tags = [
      ...new Set(tags.map((item) => item.trim()).filter(Boolean)),
    ];
  }

  /** 提交桌位表单。 */
  async function handleSubmitTable() {
    if (!options.selectedStoreId.value) return;
    const validateMessage = validateTableForm({
      tableId: options.tableForm.id,
      form: options.tableForm,
      tables: options.tables.value,
    });
    if (validateMessage) {
      message.error(validateMessage);
      return;
    }

    options.isSavingTable.value = true;
    try {
      let nextStatus: DineInTableStatus = options.tableForm.sourceStatus;
      if (options.tableForm.isDisabled) {
        nextStatus = 'disabled';
      } else if (options.tableForm.sourceStatus === 'disabled') {
        nextStatus = 'free';
      }

      const savedTable = await saveDineInTableApi({
        storeId: options.selectedStoreId.value,
        table: {
          id: options.tableForm.id || undefined,
          code: normalizeTableCode(options.tableForm.code),
          areaId: options.tableForm.areaId,
          seats: options.tableForm.seats,
          status: nextStatus,
          tags: [...options.tableForm.tags],
        },
      });

      options.tables.value =
        options.tableDrawerMode.value === 'edit' && options.tableForm.id
          ? sortTables(
              options.tables.value.map((item) =>
                item.id === options.tableForm.id ? savedTable : item,
              ),
            )
          : sortTables([...options.tables.value, savedTable]);

      options.updateSnapshot();
      options.isTableDrawerOpen.value = false;
      message.success(
        options.tableDrawerMode.value === 'edit' ? '桌位已保存' : '桌位已添加',
      );
    } catch (error) {
      console.error(error);
    } finally {
      options.isSavingTable.value = false;
    }
  }

  /** 删除桌位。 */
  async function handleDeleteTable(tableId: string) {
    if (!options.selectedStoreId.value) return;
    options.isSavingTable.value = true;
    try {
      await deleteDineInTableApi({
        storeId: options.selectedStoreId.value,
        tableId,
      });
      options.tables.value = options.tables.value.filter(
        (item) => item.id !== tableId,
      );
      options.updateSnapshot();
      message.success('桌位已删除');
    } catch (error) {
      console.error(error);
    } finally {
      options.isSavingTable.value = false;
    }
  }

  /** 打开批量生成弹窗并初始化参数。 */
  function openBatchModal() {
    options.batchForm.areaId = options.selectedTableAreaId.value;
    options.batchForm.codePrefix = 'A';
    options.batchForm.startNumber = 1;
    options.batchForm.count = 4;
    options.batchForm.seats = 4;
    options.isBatchModalOpen.value = true;
  }

  /** 控制批量弹窗显隐。 */
  function setBatchModalOpen(value: boolean) {
    options.isBatchModalOpen.value = value;
  }

  function setBatchAreaId(value: string) {
    options.batchForm.areaId = value;
  }

  function setBatchCodePrefix(value: string) {
    options.batchForm.codePrefix = value.trim().toUpperCase();
  }

  function setBatchStartNumber(value: number) {
    options.batchForm.startNumber = Math.max(1, Math.floor(Number(value || 1)));
  }

  function setBatchCount(value: number) {
    options.batchForm.count = Math.max(
      1,
      Math.min(50, Math.floor(Number(value || 1))),
    );
  }

  function setBatchSeats(value: number) {
    options.batchForm.seats = Math.max(1, Math.floor(Number(value || 1)));
  }

  /** 提交批量生成。 */
  async function handleSubmitBatch() {
    if (!options.selectedStoreId.value) return;

    const validateMessage = validateBatchForm({
      form: options.batchForm,
      existingCodes: options.tables.value.map((item) => item.code),
    });
    if (validateMessage) {
      message.error(validateMessage);
      return;
    }

    options.isSavingBatch.value = true;
    try {
      const result = await batchCreateDineInTablesApi({
        storeId: options.selectedStoreId.value,
        areaId: options.batchForm.areaId,
        codePrefix: options.batchForm.codePrefix,
        startNumber: options.batchForm.startNumber,
        count: options.batchForm.count,
        seats: options.batchForm.seats,
      });

      const createdTables: DineInTableDto[] = result.createdTables ?? [];

      options.tables.value = sortTables([
        ...options.tables.value,
        ...createdTables,
      ]);
      options.updateSnapshot();
      options.isBatchModalOpen.value = false;
      message.success(`已生成 ${createdTables.length} 张桌位`);
    } catch (error) {
      console.error(error);
    } finally {
      options.isSavingBatch.value = false;
    }
  }

  return {
    generateBatchCodes,
    handleDeleteTable,
    handleSubmitBatch,
    handleSubmitTable,
    openBatchModal,
    openTableDrawer,
    setBatchAreaId,
    setBatchCodePrefix,
    setBatchCount,
    setBatchModalOpen,
    setBatchSeats,
    setBatchStartNumber,
    setTableAreaId,
    setTableCode,
    setTableDisabled,
    setTableDrawerOpen,
    setTableSeats,
    setTableTags,
  };
}
