import type { StoreListItemDto } from '#/api/store';

/**
 * 文件职责：新客有礼页面状态与行为编排。
 * 1. 管理门店、统计、配置表单与邀请记录分页状态。
 * 2. 编排保存动作与优惠券抽屉动作。
 */
import { computed, onMounted, reactive, ref, watch } from 'vue';

import { useAccessStore } from '@vben/stores';

import {
  createDefaultNewCustomerInvitePager,
  createDefaultNewCustomerPageForm,
  createDefaultNewCustomerStats,
  NEW_CUSTOMER_MANAGE_PERMISSION,
} from './new-customer-page/constants';
import { createDataActions } from './new-customer-page/data-actions';
import { createDrawerActions } from './new-customer-page/drawer-actions';
import { createEditorActions } from './new-customer-page/editor-actions';

export function useMarketingNewCustomerPage() {
  const accessStore = useAccessStore();

  const stores = ref<StoreListItemDto[]>([]);
  const selectedStoreId = ref('');
  const isStoreLoading = ref(false);

  const isDetailLoading = ref(false);
  const isInviteLoading = ref(false);
  const isSaving = ref(false);

  const form = reactive(createDefaultNewCustomerPageForm());
  const stats = ref(createDefaultNewCustomerStats());
  const invitePager = ref(createDefaultNewCustomerInvitePager());
  const updatedAt = ref('');

  const storeOptions = computed(() =>
    stores.value.map((item) => ({
      label: item.name,
      value: item.id,
    })),
  );
  const hasStore = computed(() => stores.value.length > 0);

  const accessCodeSet = computed(
    () => new Set((accessStore.accessCodes ?? []).map(String)),
  );
  const canManage = computed(() =>
    accessCodeSet.value.has(NEW_CUSTOMER_MANAGE_PERMISSION),
  );

  function setSelectedStoreId(value: string) {
    selectedStoreId.value = value;
  }

  function setInvitePagerPage(page: number) {
    invitePager.value = {
      ...invitePager.value,
      page,
    };
  }

  function setInvitePagerPageSize(pageSize: number) {
    invitePager.value = {
      ...invitePager.value,
      pageSize,
    };
  }

  const { loadStores, loadDetail, loadInviteRecords } = createDataActions({
    stores,
    selectedStoreId,
    isStoreLoading,
    isDetailLoading,
    isInviteLoading,
    form,
    stats,
    invitePager,
    updatedAt,
  });

  const {
    removeCoupon,
    resetSettings,
    saveSettings,
    setDirectMinimumSpend,
    setDirectReduceAmount,
    setGiftEnabled,
    setGiftType,
    setInviteEnabled,
    toggleShareChannel,
  } = createEditorActions({
    canManage,
    form,
    isSaving,
    loadDetail,
    selectedStoreId,
  });

  const {
    closeCouponDrawer,
    couponDrawerForm,
    couponDrawerScene,
    isCouponDrawerOpen,
    openCouponDrawer,
    setCouponDrawerMinimumSpend,
    setCouponDrawerType,
    setCouponDrawerValidDays,
    setCouponDrawerValue,
    submitCouponDrawer,
  } = createDrawerActions({
    canManage,
    form,
  });

  async function handleInvitePageChange(page: number, pageSize: number) {
    setInvitePagerPage(page);
    setInvitePagerPageSize(pageSize);
    await loadInviteRecords();
  }

  watch(selectedStoreId, async () => {
    invitePager.value = {
      ...invitePager.value,
      page: 1,
    };
    await loadDetail(true);
  });

  onMounted(async () => {
    await loadStores();
  });

  return {
    canManage,
    closeCouponDrawer,
    couponDrawerForm,
    couponDrawerScene,
    form,
    handleInvitePageChange,
    hasStore,
    invitePager,
    isCouponDrawerOpen,
    isDetailLoading,
    isInviteLoading,
    isSaving,
    isStoreLoading,
    openCouponDrawer,
    removeCoupon,
    resetSettings,
    saveSettings,
    selectedStoreId,
    setCouponDrawerMinimumSpend,
    setCouponDrawerType,
    setCouponDrawerValidDays,
    setCouponDrawerValue,
    setDirectMinimumSpend,
    setDirectReduceAmount,
    setGiftEnabled,
    setGiftType,
    setInviteEnabled,
    setSelectedStoreId,
    stats,
    storeOptions,
    submitCouponDrawer,
    toggleShareChannel,
    updatedAt,
  };
}
