import type { ComputedRef } from 'vue';

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

/**
 * 文件职责：新客有礼券抽屉动作。
 * 1. 管理抽屉开关、字段更新与添加券行为。
 */
import { reactive, ref } from 'vue';

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

import { createDefaultNewCustomerCouponDrawerForm } from './constants';
import { normalizeCouponSort, toNullableNumber } from './helpers';

interface CreateDrawerActionsOptions {
  canManage: ComputedRef<boolean>;
  form: NewCustomerPageForm;
}

export function createDrawerActions(options: CreateDrawerActionsOptions) {
  const isCouponDrawerOpen = ref(false);
  const couponDrawerScene = ref<MarketingNewCustomerCouponScene>('welcome');
  const couponDrawerForm = reactive<NewCustomerCouponDrawerForm>(
    createDefaultNewCustomerCouponDrawerForm(),
  );

  function setCouponDrawerOpen(value: boolean) {
    isCouponDrawerOpen.value = value;
  }

  function setCouponDrawerType(
    value: NewCustomerCouponDrawerForm['couponType'],
  ) {
    couponDrawerForm.couponType = value;
    if (value === 'free_shipping') {
      couponDrawerForm.value = null;
    }
  }

  function setCouponDrawerValue(value: null | number) {
    couponDrawerForm.value = value;
  }

  function setCouponDrawerMinimumSpend(value: null | number) {
    couponDrawerForm.minimumSpend = value;
  }

  function setCouponDrawerValidDays(value: null | number) {
    couponDrawerForm.validDays = Math.max(1, Math.min(365, Number(value || 1)));
  }

  function openCouponDrawer(scene: MarketingNewCustomerCouponScene) {
    if (!options.canManage.value) {
      return;
    }

    resetCouponDrawerForm();
    couponDrawerScene.value = scene;
    isCouponDrawerOpen.value = true;
  }

  function closeCouponDrawer() {
    isCouponDrawerOpen.value = false;
  }

  function submitCouponDrawer() {
    if (!validateBeforeSubmit()) {
      return;
    }

    const next = {
      id: `draft-${Date.now()}-${Math.round(Math.random() * 1000)}`,
      scene: couponDrawerScene.value,
      couponType: couponDrawerForm.couponType,
      value:
        couponDrawerForm.couponType === 'free_shipping'
          ? null
          : toNullableNumber(couponDrawerForm.value),
      minimumSpend: toNullableNumber(couponDrawerForm.minimumSpend),
      validDays: Math.max(
        1,
        Math.min(365, Math.floor(couponDrawerForm.validDays)),
      ),
      sortOrder: 0,
    };

    if (couponDrawerScene.value === 'welcome') {
      options.form.welcomeCoupons = normalizeCouponSort('welcome', [
        ...options.form.welcomeCoupons,
        next,
      ]);
    } else if (couponDrawerScene.value === 'inviter') {
      options.form.inviterCoupons = normalizeCouponSort('inviter', [
        ...options.form.inviterCoupons,
        next,
      ]);
    } else {
      options.form.inviteeCoupons = normalizeCouponSort('invitee', [
        ...options.form.inviteeCoupons,
        next,
      ]);
    }

    isCouponDrawerOpen.value = false;
  }

  function validateBeforeSubmit() {
    const minimumSpend = toNullableNumber(couponDrawerForm.minimumSpend) ?? 0;
    if (minimumSpend < 0) {
      message.warning('使用门槛不能小于 0');
      return false;
    }

    if (couponDrawerForm.validDays < 1 || couponDrawerForm.validDays > 365) {
      message.warning('有效期必须在 1-365 天之间');
      return false;
    }

    if (couponDrawerForm.couponType === 'free_shipping') {
      return true;
    }

    const value = toNullableNumber(couponDrawerForm.value);
    if (value === null || value <= 0) {
      message.warning('请填写正确的券面额');
      return false;
    }

    if (couponDrawerForm.couponType === 'discount' && value >= 10) {
      message.warning('折扣券面额必须小于 10');
      return false;
    }

    if (
      couponDrawerForm.couponType === 'amount_off' &&
      minimumSpend > 0 &&
      value >= minimumSpend
    ) {
      message.warning('满减券减免金额必须小于使用门槛');
      return false;
    }

    return true;
  }

  function resetCouponDrawerForm() {
    const next = createDefaultNewCustomerCouponDrawerForm();
    couponDrawerForm.couponType = next.couponType;
    couponDrawerForm.value = next.value;
    couponDrawerForm.minimumSpend = next.minimumSpend;
    couponDrawerForm.validDays = next.validDays;
  }

  return {
    closeCouponDrawer,
    couponDrawerForm,
    couponDrawerScene,
    isCouponDrawerOpen,
    openCouponDrawer,
    setCouponDrawerMinimumSpend,
    setCouponDrawerOpen,
    setCouponDrawerType,
    setCouponDrawerValidDays,
    setCouponDrawerValue,
    submitCouponDrawer,
  };
}
