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

import type { MarketingNewCustomerCouponScene } from '#/api/marketing';
import type { NewCustomerPageForm } from '#/views/marketing/new-customer/types';

/**
 * 文件职责：新客有礼页面编辑与保存动作。
 * 1. 管理主表单字段更新。
 * 2. 负责保存与重置。
 */
import { message } from 'ant-design-vue';

import { saveMarketingNewCustomerSettingsApi } from '#/api/marketing';

import { buildSaveSettingsPayload, normalizeCouponSort } from './helpers';

interface CreateEditorActionsOptions {
  canManage: ComputedRef<boolean>;
  form: NewCustomerPageForm;
  isSaving: Ref<boolean>;
  loadDetail: (resetForm: boolean) => Promise<void>;
  selectedStoreId: Ref<string>;
}

export function createEditorActions(options: CreateEditorActionsOptions) {
  function setGiftEnabled(value: boolean) {
    options.form.giftEnabled = value;
  }

  function setGiftType(value: NewCustomerPageForm['giftType']) {
    options.form.giftType = value;
  }

  function setDirectReduceAmount(value: null | number) {
    options.form.directReduceAmount = value;
  }

  function setDirectMinimumSpend(value: null | number) {
    options.form.directMinimumSpend = value;
  }

  function setInviteEnabled(value: boolean) {
    options.form.inviteEnabled = value;
  }

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

    options.form.shareChannels = [...options.form.shareChannels, channel];
  }

  function removeCoupon(scene: MarketingNewCustomerCouponScene, index: number) {
    const list = resolveCouponList(scene).filter((_, idx) => idx !== index);
    applyCouponList(scene, list);
  }

  async function resetSettings() {
    await options.loadDetail(true);
  }

  async function saveSettings() {
    if (!options.canManage.value) {
      return;
    }

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

    if (!validateBeforeSubmit()) {
      return;
    }

    options.isSaving.value = true;
    try {
      await saveMarketingNewCustomerSettingsApi(
        buildSaveSettingsPayload(options.form, options.selectedStoreId.value),
      );
      message.success('新客有礼设置已保存');
      await options.loadDetail(true);
    } catch (error) {
      console.error(error);
    } finally {
      options.isSaving.value = false;
    }
  }

  function validateBeforeSubmit() {
    if (options.form.shareChannels.length === 0) {
      message.warning('请至少选择一个分享渠道');
      return false;
    }

    if (
      options.form.giftType === 'coupon' &&
      options.form.welcomeCoupons.length === 0
    ) {
      message.warning('新客礼包至少需要添加一张优惠券');
      return false;
    }

    if (options.form.giftType === 'direct') {
      if (
        options.form.directReduceAmount === null ||
        options.form.directReduceAmount <= 0
      ) {
        message.warning('首单直减金额必须大于 0');
        return false;
      }

      if (
        options.form.directMinimumSpend === null ||
        options.form.directMinimumSpend < 0
      ) {
        message.warning('首单直减使用门槛不能小于 0');
        return false;
      }
    }

    if (
      options.form.inviteEnabled &&
      (options.form.inviterCoupons.length === 0 ||
        options.form.inviteeCoupons.length === 0)
    ) {
      message.warning('开启老带新后必须配置邀请人和被邀请人奖励券');
      return false;
    }

    return true;
  }

  function resolveCouponList(scene: MarketingNewCustomerCouponScene) {
    if (scene === 'welcome') {
      return options.form.welcomeCoupons;
    }
    if (scene === 'inviter') {
      return options.form.inviterCoupons;
    }
    return options.form.inviteeCoupons;
  }

  function applyCouponList(
    scene: MarketingNewCustomerCouponScene,
    list: NewCustomerPageForm['welcomeCoupons'],
  ) {
    const normalized = normalizeCouponSort(scene, list);
    if (scene === 'welcome') {
      options.form.welcomeCoupons = normalized;
      return;
    }
    if (scene === 'inviter') {
      options.form.inviterCoupons = normalized;
      return;
    }
    options.form.inviteeCoupons = normalized;
  }

  return {
    removeCoupon,
    resetSettings,
    saveSettings,
    setDirectMinimumSpend,
    setDirectReduceAmount,
    setGiftEnabled,
    setGiftType,
    setInviteEnabled,
    toggleShareChannel,
  };
}
