import React, { useReducer, useContext, createContext, Children } from 'react';
import { action, params, todo } from '../types.dt';
export const Provider = createContext(null)
const Todos = ({ children }: {
    children: React.ReactNode
}) => {
    const reducer = (state: todo[], action: action) => {
        switch (action.type) {
            case 'Create':
                // console.log(action)

                const set = new Set([...state, { id: state.length + 1, name: action.name, completed: false }])
                const newstate = Array.from(set)
                console.log(newstate)
                return newstate;
            case "Update":
                if (action.name) {

                    state[action.index].name = action.name;
                } else {
                    state[action.index].completed = !state[action.index].completed;

                }
                return [...state];
            case "Delete":
                console.log(action.index)
                return [...state.filter((data, i) => {
                    return action.id != data.id
                })]
            default:
                return state;
        }
    }

    const initialValues: todo[] = [{
        id: 1,
        name: 'Eren Yeager',
        completed: false,
    }, {
        id: 2,
        name: "Hange Zoe",
        completed: false
    }]
    const [state, dispatch] = useReducer<todo[]>(reducer, initialValues)

    const handleCreate = (data: params): void => {
        // console.log({ ...data }, "handleCreate")
        dispatch({ type: "Create", ...data })
    }
    const handleUpdate = (data: params) => {
        dispatch({ type: "Update", ...data })
    }
    const handleDelete = (data: params) => {
        dispatch({ type: "Delete", ...data })
    }
    console.log(state)
    return (
        <Provider.Provider value={{ state, handleCreate, handleDelete, handleUpdate }}>
            {children}
        </Provider.Provider>
    )
}

export default Todos