import React from 'react'
import { configureStore, createSlice } from '@reduxjs/toolkit'
import { Provider, useSelector } from 'react-redux'

const counterSlice = createSlice({
  name: 'counter',
  initialState: {
    value: 0,
  },
  reducers: {
    increment: (state) => {
      state.value += 1
    },
    decrement: (state) => {
      state.value -= 1
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload
    },
  },
})

export const { increment, decrement, incrementByAmount } = counterSlice.actions

export const store = configureStore({
  reducer: {
    counter: counterSlice.reducer,
  },
})

export const StoreProvider: React.FC = (props) => {
  return <Provider store={store}>{props.children}</Provider>
}

export const useStore = () => {
  //@ts-ignore
  const count = useSelector((state) => state.counter.value)

  return {
    count,
    increment: () => store.dispatch(increment()),
    decrement: () => store.dispatch(decrement()),
    incrementByAmount: (value) => store.dispatch(incrementByAmount(value)),
  }
}

export const useSvelteSelector = (select, onChange) => {
  let currentState

  function handleChange() {
    let nextState = select(store.getState())
    if (nextState !== currentState) {
      currentState = nextState
      onChange(currentState)
    }
  }

  store.subscribe(handleChange)
  handleChange()
  return currentState
}
