import type { Ref } from 'vue';

import type {
  MarketingCouponChannel,
  MarketingCouponStoreScopeMode,
  MarketingCouponType,
  MarketingCouponValidityType,
} from '#/api/marketing';
import type { CouponEditorForm } from '#/views/marketing/coupon/types';

/**
 * 文件职责：优惠券编辑抽屉动作。
 * 1. 管理新增/编辑抽屉与字段更新。
 * 2. 负责详情加载、表单校验与保存提交。
 */
import { ref } from 'vue';

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

import {
  getMarketingCouponDetailApi,
  saveMarketingCouponApi,
} from '#/api/marketing';

import { createDefaultCouponEditorForm } from './constants';
import { buildSaveCouponPayload, mapDetailToEditorForm } from './helpers';

interface CreateDrawerActionsOptions {
  form: CouponEditorForm;
  isDrawerLoading: Ref<boolean>;
  isDrawerOpen: Ref<boolean>;
  isDrawerSubmitting: Ref<boolean>;
  loadCoupons: () => Promise<void>;
  selectedStoreId: Ref<string>;
}

export function createDrawerActions(options: CreateDrawerActionsOptions) {
  const drawerMode = ref<'create' | 'edit'>('create');

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

  function applyForm(next: CouponEditorForm) {
    options.form.id = next.id;
    options.form.name = next.name;
    options.form.couponType = next.couponType;
    options.form.value = next.value;
    options.form.minimumSpend = next.minimumSpend;
    options.form.totalQuantity = next.totalQuantity;
    options.form.perUserLimit = next.perUserLimit;
    options.form.validityType = next.validityType;
    options.form.validDateRange = next.validDateRange;
    options.form.relativeValidDays = next.relativeValidDays;
    options.form.channels = [...next.channels];
    options.form.storeScopeMode = next.storeScopeMode;
    options.form.storeIds = [...next.storeIds];
    options.form.status = next.status;
  }

  function resetForm() {
    applyForm(createDefaultCouponEditorForm());
  }

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

  function setFormCouponType(value: MarketingCouponType) {
    options.form.couponType = value;
    if (value === 'free_delivery') {
      options.form.value = null;
      options.form.minimumSpend = null;
    }
  }

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

  function setFormMinimumSpend(value: null | number) {
    options.form.minimumSpend = value;
  }

  function setFormTotalQuantity(value: null | number) {
    options.form.totalQuantity = value ? Math.max(0, Math.floor(value)) : 0;
  }

  function setFormPerUserLimit(value: null | number) {
    if (value === null) {
      options.form.perUserLimit = null;
      return;
    }

    options.form.perUserLimit = Math.max(0, Math.floor(value));
  }

  function setFormValidityType(value: MarketingCouponValidityType) {
    options.form.validityType = value;
    if (value === 'fixed') {
      options.form.relativeValidDays = options.form.relativeValidDays || 7;
      return;
    }

    options.form.validDateRange = null;
  }

  function setFormValidDateRange(value: CouponEditorForm['validDateRange']) {
    options.form.validDateRange = value;
  }

  function setFormRelativeValidDays(value: null | number) {
    options.form.relativeValidDays = value ? Math.max(0, Math.floor(value)) : 0;
  }

  function setFormChannels(value: MarketingCouponChannel[]) {
    options.form.channels = [...value];
  }

  function setFormStoreScopeMode(value: MarketingCouponStoreScopeMode) {
    options.form.storeScopeMode = value;
    if (value === 'all') {
      options.form.storeIds = [];
    }
  }

  function setFormStoreIds(value: string[]) {
    options.form.storeIds = [...value];
  }

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

  async function openEditDrawer(couponId: string) {
    if (!options.selectedStoreId.value) return;

    options.isDrawerLoading.value = true;
    try {
      const detail = await getMarketingCouponDetailApi({
        storeId: options.selectedStoreId.value,
        couponId,
      });

      applyForm(mapDetailToEditorForm(detail));
      drawerMode.value = 'edit';
      options.isDrawerOpen.value = true;
    } catch (error) {
      console.error(error);
    } finally {
      options.isDrawerLoading.value = false;
    }
  }

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

    options.isDrawerSubmitting.value = true;
    try {
      await saveMarketingCouponApi(
        buildSaveCouponPayload(options.form, options.selectedStoreId.value),
      );
      message.success(
        drawerMode.value === 'create' ? '优惠券已创建' : '优惠券已更新',
      );
      options.isDrawerOpen.value = false;
      await options.loadCoupons();
    } catch (error) {
      console.error(error);
    } finally {
      options.isDrawerSubmitting.value = false;
    }
  }

  function validateBeforeSubmit() {
    if (!options.form.name.trim()) {
      message.warning('请输入券名称');
      return false;
    }

    if (
      options.form.couponType !== 'free_delivery' &&
      (options.form.value === null || options.form.value <= 0)
    ) {
      message.warning('请设置正确的优惠额度');
      return false;
    }

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

    if (
      options.form.couponType === 'amount_off' &&
      (options.form.minimumSpend === null || options.form.minimumSpend <= 0)
    ) {
      message.warning('满减券必须设置使用门槛');
      return false;
    }

    if (options.form.totalQuantity <= 0) {
      message.warning('发放总量必须大于 0');
      return false;
    }

    if (options.form.perUserLimit !== null && options.form.perUserLimit <= 0) {
      message.warning('每人限领必须大于 0');
      return false;
    }

    if (options.form.validityType === 'fixed' && !options.form.validDateRange) {
      message.warning('请选择固定有效期');
      return false;
    }

    if (
      options.form.validityType === 'days' &&
      (!options.form.relativeValidDays || options.form.relativeValidDays <= 0)
    ) {
      message.warning('领取后有效天数必须大于 0');
      return false;
    }

    if (options.form.channels.length === 0) {
      message.warning('请至少选择一个适用渠道');
      return false;
    }

    if (
      options.form.storeScopeMode === 'stores' &&
      options.form.storeIds.length === 0
    ) {
      message.warning('请选择至少一个适用门店');
      return false;
    }

    return true;
  }

  return {
    drawerMode,
    openCreateDrawer,
    openEditDrawer,
    setDrawerOpen,
    setFormChannels,
    setFormCouponType,
    setFormMinimumSpend,
    setFormName,
    setFormPerUserLimit,
    setFormRelativeValidDays,
    setFormStoreIds,
    setFormStoreScopeMode,
    setFormTotalQuantity,
    setFormValidDateRange,
    setFormValidityType,
    setFormValue,
    submitDrawer,
  };
}
