import type {
  ProductDetailCategoryOption,
  ProductDetailFormState,
  ProductDetailSkuBatchState,
} from '../types';

import type {
  ProductAddonGroupDto,
  ProductDetailDto,
  ProductLabelDto,
  ProductPickerItemDto,
  ProductSpecDto,
} from '#/api/product';

import { computed, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { createProductDetailComboActions } from './product-detail-page/combo-actions';
import { DEFAULT_PRODUCT_DETAIL_FORM } from './product-detail-page/constants';
import { createProductDetailDataActions } from './product-detail-page/data-actions';
import { createProductDetailSkuActions } from './product-detail-page/sku-actions';

function isDefined<T>(value: null | T | undefined): value is T {
  return value !== null && value !== undefined;
}

export function useProductDetailPage() {
  const route = useRoute();
  const router = useRouter();

  const isLoading = ref(false);
  const isSubmitting = ref(false);
  const isUploadingImage = ref(false);
  const detail = ref<null | ProductDetailDto>(null);

  const categoryOptions = ref<ProductDetailCategoryOption[]>([]);
  const specTemplateOptions = ref<ProductSpecDto[]>([]);
  const addonGroupOptions = ref<ProductAddonGroupDto[]>([]);
  const labelOptions = ref<ProductLabelDto[]>([]);

  const comboPickerOpen = ref(false);
  const comboPickerLoading = ref(false);
  const comboPickerKeyword = ref('');
  const comboPickerProducts = ref<ProductPickerItemDto[]>([]);
  const comboPickerSelectedIds = ref<string[]>([]);
  const comboPickerCurrentGroupIndex = ref(-1);

  const skuBatch = reactive<ProductDetailSkuBatchState>({
    price: null,
    stock: null,
  });

  const form = reactive<ProductDetailFormState>({
    ...DEFAULT_PRODUCT_DETAIL_FORM,
    imageUrls: [],
    specTemplateIds: [],
    addonGroupIds: [],
    labelIds: [],
    skus: [],
    comboGroups: [],
  });

  const storeId = computed(() => String(route.query.storeId || ''));
  const productId = computed(() => String(route.query.productId || ''));

  const statusText = computed(() => {
    if (form.status === 'on_sale') return '在售';
    if (form.status === 'sold_out') return '售罄';
    return '下架';
  });

  const statusColor = computed(() => {
    if (form.status === 'on_sale') return '#52c41a';
    if (form.status === 'sold_out') return '#ef4444';
    return '#9ca3af';
  });

  const skuTemplateColumns = computed<ProductSpecDto[]>(() =>
    form.specTemplateIds
      .map((id) => specTemplateOptions.value.find((item) => item.id === id))
      .filter((item): item is ProductSpecDto => isDefined(item)),
  );

  const skuActions = createProductDetailSkuActions({
    form,
    skuBatch,
    specTemplateOptions,
  });

  const comboActions = createProductDetailComboActions({
    comboPickerCurrentGroupIndex,
    comboPickerKeyword,
    comboPickerLoading,
    comboPickerOpen,
    comboPickerProducts,
    comboPickerSelectedIds,
    form,
    storeId,
  });

  const dataActions = createProductDetailDataActions({
    addonGroupOptions,
    buildSkuRows: skuActions.buildSkuRows,
    categoryOptions,
    detail,
    form,
    isLoading,
    isSubmitting,
    isUploadingImage,
    labelOptions,
    productId,
    router,
    specTemplateOptions,
    storeId,
  });

  function goBack() {
    router.push('/product/list');
  }

  watch(
    [storeId, productId],
    () => {
      void dataActions.loadDetail();
    },
    { immediate: true },
  );

  return {
    addonGroupOptions,
    addComboGroup: comboActions.addComboGroup,
    applySkuBatchPrice: skuActions.applySkuBatchPrice,
    applySkuBatchStock: skuActions.applySkuBatchStock,
    categoryOptions,
    comboPickerCurrentGroupIndex,
    comboPickerKeyword,
    comboPickerLoading,
    comboPickerOpen,
    comboPickerProducts,
    comboPickerSelectedIds,
    comboPickerSelectedProducts: comboActions.comboPickerSelectedProducts,
    deleteCurrentProduct: dataActions.deleteCurrentProduct,
    detail,
    form,
    getOptionDisplayText: skuActions.getOptionDisplayText,
    getOptionName: skuActions.getOptionName,
    getSkuAttrOptionId: skuActions.getSkuAttrOptionId,
    getTemplateName: skuActions.getTemplateName,
    goBack,
    isLoading,
    isSubmitting,
    isUploadingImage,
    labelOptions,
    loadDetail: dataActions.loadDetail,
    openComboPicker: comboActions.openComboPicker,
    removeComboGroup: comboActions.removeComboGroup,
    removeComboItem: comboActions.removeComboItem,
    removeImage: dataActions.removeImage,
    saveDetail: dataActions.saveDetail,
    searchComboPicker: comboActions.searchComboPicker,
    setComboGroupMaxSelect: comboActions.setComboGroupMaxSelect,
    setComboGroupMinSelect: comboActions.setComboGroupMinSelect,
    setComboGroupName: comboActions.setComboGroupName,
    setComboItemQuantity: comboActions.setComboItemQuantity,
    setComboPickerOpen: comboActions.setComboPickerOpen,
    setPrimaryImage: dataActions.setPrimaryImage,
    setShelfMode: dataActions.setShelfMode,
    setSkuEnabled: skuActions.setSkuEnabled,
    setSkuOriginalPrice: skuActions.setSkuOriginalPrice,
    setSkuPrice: skuActions.setSkuPrice,
    setSkuStock: skuActions.setSkuStock,
    skuBatch,
    skuTemplateColumns,
    specTemplateOptions,
    statusColor,
    statusText,
    storeId,
    submitComboPicker: comboActions.submitComboPicker,
    toggleAddonGroup: dataActions.toggleAddonGroup,
    toggleComboPickerProduct: comboActions.toggleComboPickerProduct,
    toggleLabel: dataActions.toggleLabel,
    toggleSaleStatus: dataActions.toggleSaleStatus,
    toggleSpecTemplate: skuActions.toggleSpecTemplate,
    uploadImage: dataActions.uploadImage,
    uploadImages: dataActions.uploadImages,
  };
}
