import produce from 'immer'
import type { FC, ReactNode } from 'react'
import { useEffect, useMemo, useReducer, useRef } from 'react'
import type {
  ColorStore,
  GoodsMeta,
  ShoppingAction,

  ShoppingDispatchContextValue,
  ShoppingStateContextValue,
} from '../../context'
import {
  ShoppingDispatchContext,
  ShoppingDispatchType,
  ShoppingStateContext,
  shoppingReducer, throwError,
} from '../../context'
import { ShoppingStore } from '../../context/shoppingStore'

export interface TriggerCheckboxOptions {
  multipleSelection: GoodsMeta['multipleSelection']
  setSelectedAmount: ShoppingDispatchContextValue['UPDATE_SELECTED_AMOUNT']
}

export interface ShoppingCartPropsType {
  initialValues?: ColorStore
  onTriggerCheckbox?: (options: TriggerCheckboxOptions) => void
  children?: ReactNode
}
// 购物车上下文组件
export const ShoppingProvider: FC<ShoppingCartPropsType> = (props) => {
  const { children, onTriggerCheckbox, initialValues } = props

  const onTriggerCheckboxRef = useRef(onTriggerCheckbox)
  onTriggerCheckboxRef.current = onTriggerCheckbox
  // 发布订阅
  const Observer = useMemo(() => new ShoppingStore(), [])

  const [state, dispatch] = useReducer<(state: ShoppingStateContextValue, action: ShoppingAction) => ShoppingStateContextValue>(shoppingReducer, {
    colorStore: initialValues || {},
    currentCheckedPurchaserId: -1,
    currentCheckedSaleMode: 0,
    isManageStatus: false,
    isMultipleSelection: false,
    selectedAmount: 0,
    Observer,
  })

  // 这里要在 useEffect 也就是刷新 state 后再调用，否则如果在 onFieldsChangeRef 修改值会覆盖掉上次修改
  useEffect(() => {
    console.log('onTriggerCheckboxRef start run', state.colorStore?.[state.currentCheckedPurchaserId]?.multipleSelection)
    onTriggerCheckboxRef.current?.({
      multipleSelection: state.colorStore?.[state.currentCheckedPurchaserId]?.multipleSelection,
      setSelectedAmount: amount => dispatch({ type: ShoppingDispatchType.UPDATE_SELECTED_AMOUNT, data: amount }),
    })
  }, [state.colorStore?.[state.currentCheckedPurchaserId]?.multipleSelection])

  // 加入一个监听，为 onFieldsChange 回调服务
  // useEffect(() => {
  //   const unsubscribe = Observer.subscribe(() => {
  //     console.log('onTriggerCheckboxRef start run')
  //     onTriggerCheckboxRef.current?.({
  //       colorStore: state.colorStore,
  //       currentCheckedPurchaserId: state.currentCheckedPurchaserId,
  //       setSelectedAmount: amount => dispatch({ type: ShoppingDispatchType.UPDATE_SELECTED_AMOUNT, data: amount }),
  //     })
  //   })
  //   return unsubscribe
  // }, [Observer])

  return (
    <ShoppingStateContext.Provider value={state}>
      <ShoppingDispatchContext.Provider value={dispatch}>{children}</ShoppingDispatchContext.Provider>
    </ShoppingStateContext.Provider>
  )
}
