import type {
  DeliveryDrawerMode,
  DeliverySettingsSnapshot,
  PolygonZoneFormState,
  RadiusTierFormState,
} from '../types';

import type { StoreListItemDto } from '#/api/store';
/**
 * 文件职责：配送设置页面主编排。
 * 1. 维护页面状态与抽屉状态。
 * 2. 组装数据加载、复制、梯度、区域动作。
 * 3. 对外暴露视图层可直接消费的状态与方法。
 */
import type {
  DeliveryGeneralSettingsDto,
  DeliveryMode,
  PolygonZoneDto,
  RadiusTierDto,
} from '#/api/store-delivery';

import { computed, onActivated, onMounted, reactive, ref, watch } from 'vue';

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

import { getMerchantInfoApi } from '#/api/merchant';

import {
  DEFAULT_DELIVERY_MODE,
  DEFAULT_GENERAL_SETTINGS,
  DEFAULT_POLYGON_ZONES,
  DEFAULT_RADIUS_TIERS,
  DELIVERY_MODE_OPTIONS,
  TIER_COLOR_PALETTE,
} from './delivery-page/constants';
import { createCopyActions } from './delivery-page/copy-actions';
import { createDataActions } from './delivery-page/data-actions';
import {
  cloneGeneralSettings,
  clonePolygonZones,
  cloneRadiusTiers,
  createTierId,
  createZoneId,
  formatCurrency,
  formatDistanceRange,
  getTierColorByIndex,
  sortPolygonZones,
  sortRadiusTiers,
} from './delivery-page/helpers';
import { createTierActions } from './delivery-page/tier-actions';
import { createZoneActions } from './delivery-page/zone-actions';

export function useStoreDeliveryPage() {
  function buildRegionText(
    province?: string,
    city?: string,
    district?: string,
  ) {
    return [province, city, district]
      .map((part) => part?.trim() ?? '')
      .filter(Boolean)
      .join('');
  }

  // 1. 页面 loading / submitting 状态。
  const isStoreLoading = ref(false);
  const isSettingsLoading = ref(false);
  const isSaving = ref(false);
  const isCopySubmitting = ref(false);
  const isConfigured = ref(false);
  const loadedStoreId = ref('');

  // 2. 页面主业务数据。
  const stores = ref<StoreListItemDto[]>([]);
  const selectedStoreId = ref('');
  // 当前生效配送模式（会落库）。
  const deliveryMode = ref<DeliveryMode>(DEFAULT_DELIVERY_MODE);
  // 当前编辑视图模式（仅影响页面展示，不直接落库）。
  const editingMode = ref<DeliveryMode>(DEFAULT_DELIVERY_MODE);
  // 半径配送中心点（仅半径模式使用）。
  const radiusCenterLatitude = ref<null | number>(null);
  const radiusCenterLongitude = ref<null | number>(null);
  const radiusTiers = ref<RadiusTierDto[]>(
    cloneRadiusTiers(DEFAULT_RADIUS_TIERS),
  );
  const polygonZones = ref<PolygonZoneDto[]>(
    clonePolygonZones(DEFAULT_POLYGON_ZONES),
  );
  const generalSettings = reactive<DeliveryGeneralSettingsDto>(
    cloneGeneralSettings(DEFAULT_GENERAL_SETTINGS),
  );
  const merchantCityText = ref('');
  const merchantRegisteredAddress = ref('');

  // 3. 页面弹窗与抽屉状态。
  const isCopyModalOpen = ref(false);
  const copyTargetStoreIds = ref<string[]>([]);
  const snapshot = ref<DeliverySettingsSnapshot | null>(null);

  const isTierDrawerOpen = ref(false);
  const tierDrawerMode = ref<DeliveryDrawerMode>('create');
  const tierForm = reactive<RadiusTierFormState>({
    id: '',
    minDistance: 0,
    maxDistance: 1,
    deliveryFee: 5,
    etaMinutes: 30,
    minOrderAmount: 20,
    color: getTierColorByIndex(0),
  });

  const isZoneDrawerOpen = ref(false);
  const zoneDrawerMode = ref<DeliveryDrawerMode>('create');
  const zoneForm = reactive<PolygonZoneFormState>({
    id: '',
    name: '',
    deliveryFee: 5,
    minOrderAmount: 20,
    etaMinutes: 30,
    priority: 1,
    color: getTierColorByIndex(0),
    polygonGeoJson: '',
  });

  // 4. 页面衍生视图数据。
  const storeOptions = computed(() =>
    stores.value.map((store) => ({ label: store.name, value: store.id })),
  );

  const selectedStoreName = computed(
    () =>
      stores.value.find((store) => store.id === selectedStoreId.value)?.name ??
      '',
  );
  const selectedStore = computed(
    () =>
      stores.value.find((store) => store.id === selectedStoreId.value) ?? null,
  );
  const mapCenterLatitude = computed(
    () => selectedStore.value?.latitude ?? null,
  );
  const mapCenterLongitude = computed(
    () => selectedStore.value?.longitude ?? null,
  );
  const mapCenterAddress = computed(() => {
    const store = selectedStore.value;
    if (!store) return '';

    const normalizedAddress = store.address?.trim() ?? '';
    if (normalizedAddress) return normalizedAddress;

    return buildRegionText(store.province, store.city, store.district);
  });
  const mapFallbackCityText = computed(() => {
    const store = selectedStore.value;
    const storeCityText = buildRegionText(
      store?.province,
      store?.city,
      store?.district,
    );

    if (storeCityText) return storeCityText;
    if (merchantCityText.value) return merchantCityText.value;
    return merchantRegisteredAddress.value;
  });

  const copyCandidates = computed(() =>
    stores.value.filter((store) => store.id !== selectedStoreId.value),
  );

  const isCopyAllChecked = computed(
    () =>
      copyCandidates.value.length > 0 &&
      copyTargetStoreIds.value.length === copyCandidates.value.length,
  );

  const isCopyIndeterminate = computed(
    () =>
      copyTargetStoreIds.value.length > 0 &&
      copyTargetStoreIds.value.length < copyCandidates.value.length,
  );

  const isRadiusMode = computed(() => editingMode.value === 'radius');
  const isPageLoading = computed(() => isSettingsLoading.value);
  const hasSelectedStore = computed(() => Boolean(selectedStoreId.value));
  const hasLoadedStoreSettings = computed(
    () =>
      loadedStoreId.value === selectedStoreId.value && snapshot.value !== null,
  );
  const canOperate = computed(
    () =>
      hasSelectedStore.value &&
      loadedStoreId.value === selectedStoreId.value &&
      !isStoreLoading.value &&
      !isSettingsLoading.value &&
      !isSaving.value,
  );

  const tierDrawerTitle = computed(() =>
    tierDrawerMode.value === 'edit' ? '编辑梯度' : '添加梯度',
  );
  const zoneDrawerTitle = computed(() =>
    zoneDrawerMode.value === 'edit' ? '编辑区域' : '新增区域',
  );

  function clearSettings() {
    deliveryMode.value = DEFAULT_DELIVERY_MODE;
    editingMode.value = DEFAULT_DELIVERY_MODE;
    radiusCenterLatitude.value = null;
    radiusCenterLongitude.value = null;
    radiusTiers.value = cloneRadiusTiers(DEFAULT_RADIUS_TIERS);
    polygonZones.value = clonePolygonZones(DEFAULT_POLYGON_ZONES);
    Object.assign(
      generalSettings,
      cloneGeneralSettings(DEFAULT_GENERAL_SETTINGS),
    );
  }

  // 5. 数据域动作装配。
  const {
    loadStoreSettings,
    loadStores,
    resetFromSnapshot,
    saveCurrentSettings,
  } = createDataActions({
    clearSettings,
    editingMode,
    generalSettings,
    isConfigured,
    isSaving,
    isSettingsLoading,
    isStoreLoading,
    loadedStoreId,
    mode: deliveryMode,
    radiusCenterLatitude,
    radiusCenterLongitude,
    polygonZones,
    radiusTiers,
    selectedStoreId,
    snapshot,
    stores,
  });

  const {
    handleCopyCheckAll,
    handleCopySubmit,
    openCopyModal,
    toggleCopyStore,
  } = createCopyActions({
    copyCandidates,
    copyTargetStoreIds,
    isCopyModalOpen,
    isCopySubmitting,
    selectedStoreId,
  });

  const {
    handleDeleteTier: handleDeleteTierLocal,
    handleTierSubmit: handleTierSubmitLocal,
    openTierDrawer,
    setTierColor,
    setTierDeliveryFee,
    setTierDrawerOpen,
    setTierEtaMinutes,
    setTierMaxDistance,
    setTierMinDistance,
    setTierMinOrderAmount,
  } = createTierActions({
    createTierId,
    getTierColorByIndex,
    isTierDrawerOpen,
    radiusTiers,
    sortRadiusTiers,
    tierDrawerMode,
    tierForm,
  });

  const {
    handleDeleteZone: handleDeleteZoneLocal,
    handleZoneSubmit: handleZoneSubmitLocal,
    openZoneDrawer,
    setZoneColor,
    setZoneDeliveryFee,
    setZoneDrawerOpen,
    setZoneEtaMinutes,
    setZoneMinOrderAmount,
    setZoneName,
    setZonePolygonGeoJson,
    setZonePriority,
  } = createZoneActions({
    createZoneId,
    getTierColorByIndex,
    isZoneDrawerOpen,
    polygonZones,
    sortPolygonZones,
    zoneDrawerMode,
    zoneForm,
  });

  // 6. 页面字段更新方法。
  function setSelectedStoreId(value: string) {
    selectedStoreId.value = value;
  }

  // 切换“配置编辑视图”，不直接修改生效模式。
  function setEditingMode(value: DeliveryMode) {
    editingMode.value = value;
  }

  function setRadiusCenterLatitude(value: null | number) {
    if (value === null || value === undefined) {
      radiusCenterLatitude.value = null;
      return;
    }
    radiusCenterLatitude.value = Number(value);
  }

  function setRadiusCenterLongitude(value: null | number) {
    if (value === null || value === undefined) {
      radiusCenterLongitude.value = null;
      return;
    }
    radiusCenterLongitude.value = Number(value);
  }

  // 切换“当前生效模式”，二次确认后保存，防止误操作。
  function setDeliveryMode(value: DeliveryMode) {
    if (!canOperate.value) return;
    if (value === deliveryMode.value) return;
    Modal.confirm({
      title: '确认切换当前启用的配送模式？',
      content:
        value === 'radius'
          ? '切换后将使用按半径配送规则进行计费与可达性判断。'
          : '切换后将使用按区域配送（多边形）规则进行计费与可达性判断。',
      okText: '确认切换',
      cancelText: '取消',
      async onOk() {
        const previousMode = deliveryMode.value;
        const previousEditingMode = editingMode.value;
        deliveryMode.value = value;
        editingMode.value = value;
        const saved = await saveCurrentSettings();
        if (!saved) {
          deliveryMode.value = previousMode;
          editingMode.value = previousEditingMode;
        }
      },
    });
  }

  function setFreeDeliveryThreshold(value: null | number) {
    if (value === null || value === undefined) {
      generalSettings.freeDeliveryThreshold = null;
      return;
    }
    generalSettings.freeDeliveryThreshold = Math.max(0, Number(value || 0));
  }

  function setMaxDeliveryDistance(value: number) {
    generalSettings.maxDeliveryDistance = Math.max(0, Number(value || 0));
  }

  function setHourlyCapacityLimit(value: number) {
    generalSettings.hourlyCapacityLimit = Math.max(
      1,
      Math.floor(Number(value || 1)),
    );
  }

  function setEtaAdjustmentMinutes(value: number) {
    generalSettings.etaAdjustmentMinutes = Math.max(
      0,
      Math.floor(Number(value || 0)),
    );
  }

  async function loadMerchantLocation() {
    try {
      const result = await getMerchantInfoApi();
      const merchant = result.merchant;

      merchantCityText.value = buildRegionText(
        merchant?.province,
        merchant?.city,
        merchant?.district,
      );
      merchantRegisteredAddress.value =
        merchant?.registeredAddress?.trim() ?? '';
    } catch (error) {
      console.error(error);
      merchantCityText.value = '';
      merchantRegisteredAddress.value = '';
    }
  }

  async function handleTierSubmit() {
    if (!canOperate.value) return;
    const changed = handleTierSubmitLocal();
    if (!changed) return;
    await saveCurrentSettings();
  }

  async function handleDeleteTier(tierId: string) {
    if (!canOperate.value) return;
    const changed = handleDeleteTierLocal(tierId);
    if (!changed) return;
    await saveCurrentSettings();
  }

  async function handleZoneSubmit() {
    if (!canOperate.value) return;
    const changed = handleZoneSubmitLocal();
    if (!changed) return;
    await saveCurrentSettings();
  }

  async function handleDeleteZone(zoneId: string) {
    if (!canOperate.value) return;
    const changed = handleDeleteZoneLocal(zoneId);
    if (!changed) return;
    await saveCurrentSettings();
  }

  // 7. 门店切换时自动刷新配置。
  watch(selectedStoreId, async (storeId) => {
    if (!storeId) {
      loadedStoreId.value = '';
      isConfigured.value = false;
      clearSettings();
      snapshot.value = null;
      return;
    }
    loadedStoreId.value = '';
    isConfigured.value = false;
    snapshot.value = null;
    clearSettings();
    await loadStoreSettings(storeId);
  });

  async function loadPageContext() {
    await Promise.allSettled([loadStores(), loadMerchantLocation()]);
  }

  // 8. 页面首屏初始化。
  onMounted(loadPageContext);
  // 9. 路由回到当前页时刷新门店列表，避免使用旧缓存。
  onActivated(loadPageContext);

  return {
    DELIVERY_MODE_OPTIONS,
    canOperate,
    copyCandidates,
    copyTargetStoreIds,
    deliveryMode,
    editingMode,
    formatCurrency,
    formatDistanceRange,
    generalSettings,
    handleCopyCheckAll,
    handleCopySubmit,
    handleDeleteTier,
    handleDeleteZone,
    handleTierSubmit,
    handleZoneSubmit,
    isCopyAllChecked,
    isCopyIndeterminate,
    isCopyModalOpen,
    isCopySubmitting,
    isConfigured,
    hasLoadedStoreSettings,
    hasSelectedStore,
    isPageLoading,
    isRadiusMode,
    isSaving,
    isStoreLoading,
    isTierDrawerOpen,
    isZoneDrawerOpen,
    mapCenterAddress,
    mapCenterLatitude,
    mapCenterLongitude,
    mapFallbackCityText,
    openCopyModal,
    openTierDrawer,
    openZoneDrawer,
    loadedStoreId,
    polygonZones,
    radiusCenterLatitude,
    radiusCenterLongitude,
    radiusTiers,
    resetFromSnapshot,
    saveCurrentSettings,
    selectedStoreId,
    selectedStoreName,
    setDeliveryMode,
    setEditingMode,
    setEtaAdjustmentMinutes,
    setFreeDeliveryThreshold,
    setHourlyCapacityLimit,
    setMaxDeliveryDistance,
    setRadiusCenterLatitude,
    setRadiusCenterLongitude,
    setSelectedStoreId,
    setTierColor,
    setTierDeliveryFee,
    setTierDrawerOpen,
    setTierEtaMinutes,
    setTierMaxDistance,
    setTierMinDistance,
    setTierMinOrderAmount,
    setZoneColor,
    setZoneDeliveryFee,
    setZoneDrawerOpen,
    setZoneEtaMinutes,
    setZoneMinOrderAmount,
    setZoneName,
    setZonePolygonGeoJson,
    setZonePriority,
    storeOptions,
    tierColorPalette: TIER_COLOR_PALETTE,
    tierDrawerMode,
    tierDrawerTitle,
    tierForm,
    toggleCopyStore,
    zoneDrawerMode,
    zoneDrawerTitle,
    zoneForm,
  };
}
