import type { Ref } from 'vue';

import type {
  ProductScheduleCardViewModel,
  ScheduleEditorForm,
} from '#/views/product/schedule/types';

/**
 * 文件职责：时段规则编辑抽屉动作。
 */
import { message } from 'ant-design-vue';

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

import {
  createDefaultScheduleForm,
  normalizeWeekDays,
  WEEK_DAYS_ALL,
  WEEK_DAYS_WEEKDAY,
  WEEK_DAYS_WEEKEND,
} from './constants';
import { isValidTimeText } from './timeline-utils';

interface CreateDrawerActionsOptions {
  drawerMode: Ref<'create' | 'edit'>;
  editingScheduleId: Ref<string>;
  form: ScheduleEditorForm;
  isDrawerOpen: Ref<boolean>;
  isDrawerSubmitting: Ref<boolean>;
  isPickerOpen: Ref<boolean>;
  loadPickerProducts: () => Promise<void>;
  loadSchedules: () => Promise<void>;
  pickerKeyword: Ref<string>;
  pickerSelectedIds: Ref<string[]>;
  rows: Ref<ProductScheduleCardViewModel[]>;
  selectedStoreId: Ref<string>;
}

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

  function setPickerOpen(value: boolean) {
    options.isPickerOpen.value = value;
  }

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

  function setFormStartTime(value: string) {
    options.form.startTime = value;
  }

  function setFormEndTime(value: string) {
    options.form.endTime = value;
  }

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

  function setFormWeekDays(value: number[]) {
    options.form.weekDays = normalizeWeekDays(value);
  }

  function toggleWeekDay(day: number) {
    if (options.form.weekDays.includes(day)) {
      setFormWeekDays(options.form.weekDays.filter((item) => item !== day));
      return;
    }

    setFormWeekDays([...options.form.weekDays, day]);
  }

  function selectAllDays() {
    setFormWeekDays([...WEEK_DAYS_ALL]);
  }

  function selectWeekdays() {
    setFormWeekDays([...WEEK_DAYS_WEEKDAY]);
  }

  function selectWeekend() {
    setFormWeekDays([...WEEK_DAYS_WEEKEND]);
  }

  function removeFormProduct(productId: string) {
    options.form.productIds = options.form.productIds.filter(
      (item) => item !== productId,
    );
  }

  function setPickerKeyword(value: string) {
    options.pickerKeyword.value = value;
  }

  function togglePickerProduct(productId: string) {
    if (options.pickerSelectedIds.value.includes(productId)) {
      options.pickerSelectedIds.value = options.pickerSelectedIds.value.filter(
        (item) => item !== productId,
      );
      return;
    }

    options.pickerSelectedIds.value = [
      ...options.pickerSelectedIds.value,
      productId,
    ];
  }

  async function openProductPicker() {
    if (!options.selectedStoreId.value) {
      return;
    }

    options.pickerKeyword.value = '';
    options.pickerSelectedIds.value = [...options.form.productIds];
    await options.loadPickerProducts();
    options.isPickerOpen.value = true;
  }

  function submitPicker() {
    options.form.productIds = [...options.pickerSelectedIds.value];
    options.isPickerOpen.value = false;
  }

  function resetForm() {
    const next = createDefaultScheduleForm();
    options.editingScheduleId.value = '';
    options.form.id = '';
    options.form.name = next.name;
    options.form.startTime = next.startTime;
    options.form.endTime = next.endTime;
    options.form.weekDays = [...next.weekDays];
    options.form.productIds = [];
    options.form.status = next.status;
  }

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

  function openEditDrawer(item: ProductScheduleCardViewModel) {
    options.drawerMode.value = 'edit';
    options.editingScheduleId.value = item.id;
    options.form.id = item.id;
    options.form.name = item.name;
    options.form.startTime = item.startTime;
    options.form.endTime = item.endTime;
    options.form.weekDays = [...item.weekDays];
    options.form.productIds = [...item.productIds];
    options.form.status = item.status;
    options.isDrawerOpen.value = true;
  }

  async function submitDrawer() {
    if (!options.selectedStoreId.value) return;

    const normalizedName = options.form.name.trim();
    if (!normalizedName) {
      message.warning('请输入规则名称');
      return;
    }

    if (!isValidTimeText(options.form.startTime)) {
      message.warning('开始时间格式不正确');
      return;
    }

    if (!isValidTimeText(options.form.endTime)) {
      message.warning('结束时间格式不正确');
      return;
    }

    if (options.form.startTime === options.form.endTime) {
      message.warning('开始和结束时间不能相同');
      return;
    }

    const normalizedWeekDays = normalizeWeekDays(options.form.weekDays);
    if (normalizedWeekDays.length === 0) {
      message.warning('请至少选择一个适用星期');
      return;
    }

    const normalizedProductIds = [...new Set(options.form.productIds)];
    if (normalizedProductIds.length === 0) {
      message.warning('请至少关联一个商品');
      return;
    }

    options.isDrawerSubmitting.value = true;
    try {
      await saveProductScheduleApi({
        storeId: options.selectedStoreId.value,
        id: options.editingScheduleId.value || undefined,
        name: normalizedName,
        startTime: options.form.startTime,
        endTime: options.form.endTime,
        weekDays: normalizedWeekDays,
        productIds: normalizedProductIds,
        status: options.form.status,
      });

      message.success(
        options.drawerMode.value === 'create'
          ? '时段规则已创建'
          : '时段规则已更新',
      );
      options.isDrawerOpen.value = false;
      await options.loadSchedules();
    } catch (error) {
      console.error(error);
    } finally {
      options.isDrawerSubmitting.value = false;
    }
  }

  return {
    openCreateDrawer,
    openEditDrawer,
    openProductPicker,
    removeFormProduct,
    selectAllDays,
    selectWeekdays,
    selectWeekend,
    setDrawerOpen,
    setFormEndTime,
    setFormName,
    setFormStartTime,
    setPickerKeyword,
    setPickerOpen,
    submitDrawer,
    submitPicker,
    toggleFormStatus,
    togglePickerProduct,
    toggleWeekDay,
  };
}
