import {useEffect, useReducer, useState} from "react";
import {SimpleReducer} from "../../utils/SimpleReducer.jsx";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faAdd, faTrashCan} from "@fortawesome/free-solid-svg-icons";
import {useTranslation} from "react-i18next";

function timeNumberToSting(nbMin) {
    return String(Math.floor(nbMin / 60)).padStart(2, '0') + ":" + String(nbMin % 60).padStart(2, '0')
}

function timeStringToNumber(time) {
    let times = time.split(':');
    return parseInt(times[0]) * 60 + parseInt(times[1]);
}

export function HoraireEditor({data}) {
    const [state, dispatch] = useReducer(SimpleReducer, [])
    const [out_data, setOutData] = useState({})
    const {t} = useTranslation();

    useEffect(() => {
        if (data.training_day_time === null)
            return
        JSON.parse(data.training_day_time).forEach((d, index) => {
            dispatch({type: 'UPDATE_OR_ADD', payload: {id: index, data: d}})
        })
    }, [data.training_day_time]);

    useEffect(() => {
        setOutData(state.map(d => {
            return {day: d.data.day, time_start: d.data.time_start, time_end: d.data.time_end}
        }))
    }, [state]);

    const sortHoraire = (a, b) => {
        if (a.data.day === b.data.day)
            return a.data.time_start - b.data.time_start;
        return a.data.day - b.data.day;
    }

    return <div className="row mb-3">
        <input name="training_day_time" value={JSON.stringify(out_data)} readOnly hidden/>
        <span className="input-group-text">{t("horairesD'entraînements")}</span>
        <ul className="list-group form-control">
            {state.map((d, index) => {
                return <div key={index} className="input-group">
                    <select className="form-select" aria-label="type" value={d.data.day}
                            onChange={(e) => {
                                d.data.day = Number(e.target.value)
                                dispatch({type: 'UPDATE_OR_ADD', payload: {id: d.id, data: d.data}})
                                dispatch({type: 'SORT', payload: sortHoraire})
                            }}>
                        <option value="0">{t('days.0')}</option>
                        <option value="1">{t('days.1')}</option>
                        <option value="2">{t('days.2')}</option>
                        <option value="3">{t('days.3')}</option>
                        <option value="4">{t('days.4')}</option>
                        <option value="5">{t('days.5')}</option>
                        <option value="6">{t('days.6')}</option>
                    </select>
                    <span className="input-group-text">{t('de')}</span>
                    <input type="time" className="form-control" value={timeNumberToSting(d.data.time_start)} required
                           onChange={(e) => {
                               d.data.time_start = timeStringToNumber(e.target.value)
                               dispatch({type: 'UPDATE_OR_ADD', payload: {id: d.id, data: d.data}})
                               dispatch({type: 'SORT', payload: sortHoraire})
                           }}/>
                    <span className="input-group-text">{t('à')}</span>
                    <input type="time" className="form-control" value={timeNumberToSting(d.data.time_end)} required
                           onChange={(e) => {
                               d.data.time_end = timeStringToNumber(e.target.value)
                               dispatch({type: 'UPDATE_OR_ADD', payload: {id: d.id, data: d.data}})
                               dispatch({type: 'SORT', payload: sortHoraire})
                           }}/>
                    <button className="btn btn-danger" type="button"
                            onClick={() => dispatch({type: 'REMOVE', payload: d.id})}>
                        <FontAwesomeIcon icon={faTrashCan}/>
                    </button>
                </div>
            })}
            <div className="d-grid gap-2 d-md-flex justify-content-md-end">
                <button className="btn btn-success" type="button"
                        disabled={state.length >= 21}
                        onClick={() => {
                            let maxId = 0;
                            state.forEach((d) => {
                                if (d.id > maxId)
                                    maxId = d.id;
                            })
                            dispatch({type: 'UPDATE_OR_ADD', payload: {id: maxId + 1, data: {day: 6, time_start: 0, time_end: 0}}})
                        }}>
                    <FontAwesomeIcon icon={faAdd}/>
                </button>
            </div>
        </ul>
    </div>
}
