import React, {useReducer} from 'react';

// 定义状态的类型
type CounterState = {
	count: number;
};

// 定义要执行的动作的类型
type CounterAction = { type: 'increment'; amount: number }
	| { type: 'decrement'; amount: number }
	| { type: 'reset' };

// 使用Reducer函数处理状态变化
function counterReducer(state: CounterState, action: CounterAction): CounterState {

	switch (action.type) {
		case 'increment':
			return {count: state.count + action.amount};
		case 'decrement':
			return {count: state.count - action.amount};
		case 'reset':
			return {count: 0};
		default:
			throw new Error(`Unhandled action type`);
	}
}

// 使用useReducer钩子
export const Counter: React.FC = () => {
	const [state, dispatch] = useReducer(counterReducer, {count: 0});

	return (
		<div>
			Value: {state.count}
			<button onClick={() => dispatch({type: 'increment', amount: 1})}>Increment</button>
			<button disabled={state.count <= 0} onClick={() => dispatch({type: 'decrement', amount: 1})}>Decrement</button>
			<button onClick={() => dispatch({type: 'reset'})}>Reset</button>
		</div>
	);
};
