import {useLoadingSwitcher} from "../../../hooks/useLoading.jsx";
import {useFetch} from "../../../hooks/useFetch.js";
import {useEffect, useReducer, useState} from "react";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faEye, faFilePdf, faPen} from "@fortawesome/free-solid-svg-icons";
import {AxiosError} from "../../../components/AxiosError.jsx";
import {apiAxios, getSaison, getToastMessage} from "../../../utils/Tools.js";
import {toast} from "react-toastify";
import {SimpleReducer} from "../../../utils/SimpleReducer.jsx";
import {useNavigate} from "react-router-dom";
import {useTranslation} from "react-i18next";

const vite_url = import.meta.env.VITE_URL;

export function AffiliationCard({clubData}) {
    const setLoading = useLoadingSwitcher()
    const {data, error} = useFetch(`/affiliation/${clubData.id}`, setLoading, 1)
    const {t} = useTranslation();

    const [modalAffiliation, setModal] = useState({id: 0, club: clubData.id})
    const [affiliations, dispatch] = useReducer(SimpleReducer, [])

    useEffect(() => {
        if (!data) return
        for (const dataKey of data) {
            dispatch({type: 'UPDATE_OR_ADD', payload: dataKey})
        }
        dispatch({type: 'SORT', payload: (a, b) => b.saison - a.saison})
    }, [data]);

    return <div className="card mb-4">
        <div className="card-header container-fluid">
            <div className="row">
                <div className="col">{t('affiliation')}</div>
                <div className="col" style={{textAlign: 'right'}}>
                    <button className="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#AffiliationModal"
                            onClick={_ => setModal({id: 0, club: clubData.id, validate: 1})}>{t('button.ajouter')}
                    </button>
                </div>
            </div>
        </div>
        <div className="card-body">
            <ul className="list-group">
                {affiliations.map((affiliation, index) => {
                    return <div key={index}
                                className={"list-group-item d-flex justify-content-between align-items-start list-group-item-" +
                                    (affiliation.validate ? "success" : "warning")}>
                        <div className="me-auto">{affiliation?.saison}-{affiliation?.saison + 1}</div>
                        <button className="badge btn btn-primary rounded-pill" data-bs-toggle="modal"
                                data-bs-target="#AffiliationModal" onClick={_ => setModal(affiliation)}>
                            <FontAwesomeIcon icon={faPen}/></button>
                    </div>
                })}
                {error && <AxiosError error={error}/>}
            </ul>

            <a href={`${vite_url}/api/club/${clubData.id}/affiliation`} target='#'>
                <button className="btn btn-primary" type="button" id="button-addon1" style={{marginTop: '1em'}}
                        onClick={() => null}>
                    {t('dlAff')} <FontAwesomeIcon icon={faFilePdf}></FontAwesomeIcon>
                </button>
            </a>
        </div>

        <div className="modal fade" id="AffiliationModal" tabIndex="-1" aria-labelledby="AffiliationModalLabel"
             aria-hidden="true">
            <div className="modal-dialog">
                <div className="modal-content">
                    <ModalContent affiliation={modalAffiliation} dispatch={dispatch}/>
                </div>
            </div>
        </div>
    </div>;
}

function sendAffiliation(event, dispatch) {
    event.preventDefault();

    const formData = new FormData(event.target);
    toast.promise(
        apiAxios.post(`/affiliation/${formData.get('club')}?saison=${formData.get('saison')}`), getToastMessage('aff.toast.save2')
    ).then(data => {
        dispatch({type: 'UPDATE_OR_ADD', payload: data.data})
        dispatch({type: 'SORT', payload: (a, b) => b.saison - a.saison})
    })

}

function removeAffiliation(id, dispatch) {
    if (id <= 0) return
    toast.promise(
        apiAxios.delete(`/affiliation/${id}`), getToastMessage('aff.toast.del2')
    ).then(_ => {
        dispatch({type: 'REMOVE', payload: id})
    })
}

function ModalContent({affiliation, dispatch}) {
    const navigate = useNavigate();
    const [saison, setSaison] = useState(0)
    const {t} = useTranslation();
    const setSeason = (event) => {
        setSaison(Number(event.target.value))
    }

    useEffect(() => {
        if (affiliation.id !== 0) {
            setSaison(affiliation.saison)
        } else {
            setSaison(getSaison())
        }
    }, [affiliation]);

    return <form onSubmit={e => sendAffiliation(e, dispatch)}>
        <input name="id" value={affiliation.id} readOnly hidden/>
        <input name="club" value={affiliation.club} readOnly hidden/>
        <div className="modal-header">
            <h1 className="modal-title fs-5" id="AffiliationModalLabel">{t("editionDeL'affiliation")}</h1>
            <button type="button" className="btn-close" data-bs-dismiss="modal"
                    aria-label="Close"></button>
        </div>
        <div className="modal-body">
            <div className="input-group mb-3  justify-content-md-center">
                {affiliation.id === 0
                    ? <input type="number" className="form-control" placeholder={t('saison')} name="saison"
                             aria-label="Saison" aria-describedby="basic-addon2" value={saison} onChange={setSeason}/>
                    : <><span className="input-group-text" id="basic-addon2">{saison}</span>
                        <input name="saison" value={saison} readOnly hidden/></>}
                <span className="input-group-text" id="basic-addon2">-</span>
                <span className="input-group-text" id="basic-addon2">{saison + 1}</span>
            </div>
            <div className="input-group mb-3  justify-content-md-center">
                <span className="input-group-text" id="basic-addon2">{t('étatDeLaDemande')}</span>
                {affiliation.validate ? <span className="input-group-text" id="basic-addon2">{t('validée')}</span> :
                    <>
                        <span className="input-group-text" id="basic-addon2">{t('enAttente')}</span>
                        <button type="button" className="btn btn-primary"
                                onClick={() => navigate('/admin/affiliation/request/' + (affiliation.id * -1))}
                                data-bs-dismiss="modal"><FontAwesomeIcon icon={faEye}/></button>
                    </>}
            </div>
        </div>
        <div className="modal-footer">
            {affiliation.id === 0 && <button type="submit" className="btn btn-primary" data-bs-dismiss="modal">{t('button.enregistrer')}</button>}
            <button type="reset" className="btn btn-secondary" data-bs-dismiss="modal">{t('button.fermer')}</button>
            {affiliation.id <= 0 || <button type="button" className="btn btn-danger" data-bs-dismiss="modal"
                                            onClick={() => removeAffiliation(affiliation.id, dispatch)}>{t('button.supprimer')}</button>}
        </div>
    </form>
}
