import {useEffect, useReducer, useState} from "react";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faPen, faTrashCan} from "@fortawesome/free-solid-svg-icons";
import {AxiosError} from "./AxiosError.jsx";

function SimpleReducer(datas, action) {
    switch (action.type) {
        case 'ADD':
            return [
                ...datas,
                action.payload
            ]
        case 'REMOVE':
            return datas.filter(data => data.id !== action.payload)
        case 'UPDATE_OR_ADD':
            const index = datas.findIndex(data => data.id === action.payload.id)
            if (index === -1) {
                return [
                    ...datas,
                    action.payload
                ]
            } else {
                datas[index] = action.payload
                return [...datas]
            }
        default:
            throw new Error()
    }
}

export function ListEditorTest() {
    const [html, dispatch] = ListEditor(ListHTML)

    useEffect(() => {
        dispatch({type: 'UPDATE_OR_ADD', payload: {id: 1, content: "data in"}})
    }, []);

    return html
}

export function ListEditor(ListItem) {
    const [modal, setModal] = useState({id: -1})
    const [state, dispatch] = useReducer(SimpleReducer, [])

    const sendAffiliation = (e) => {

        dispatch({type: 'UPDATE_OR_ADD', payload: e})
    }

    return [<>
        <ul className="list-group">
            {state.map((d, index) => {
                return <div key={index} className={"list-group-item d-flex justify-content-between align-items-start"}>
                    <ListItem data={d}/>
                    <button className="badge btn btn-primary rounded-pill" data-bs-toggle="modal"
                            data-bs-target="#EditModal" onClick={_ => setModal(d)}>
                        <FontAwesomeIcon icon={faPen}/></button>
                    <button className="badge btn btn-danger rounded-pill"
                            onClick={() => dispatch({type: 'REMOVE', payload: d.id})}>
                        <FontAwesomeIcon icon={faTrashCan}/></button>
                </div>
            })}
        </ul>
        <div className="modal fade" id="EditModal" tabIndex="-1" aria-labelledby="EditModalLabel"
             aria-hidden="true">
            <div className="modal-dialog">
                <div className="modal-content">
                    <form onSubmit={e => sendAffiliation(e, dispatch)}>
                        <input name="id" value={modal.id} readOnly hidden/>
                    </form>
                        <ModalContent affiliation={modalAffiliation} dispatch={dispatch}/>
                </div>
            </div>
        </div>
    </>
, dispatch]
}

function ListHTML({
    data
}) {
    return <div className="me-auto">{data.content}</div>
}