import {useNavigate, useParams} from "react-router-dom";
import {useLoadingSwitcher} from "../../hooks/useLoading.jsx";
import {useFetch} from "../../hooks/useFetch.js";
import {AxiosError} from "../../components/AxiosError.jsx";
import {useAuth} from "../../hooks/useAuth.jsx";
import {apiAxios, applyOverCategory, getCatName, getToastMessage, isClubAdmin} from "../../utils/Tools.js";
import {ThreeDots} from "react-loader-spinner";
import React, {useEffect, useState} from "react";
import {toast} from "react-toastify";
import {useTranslation} from "react-i18next";
import i18n from "i18next";

export function CompetitionView() {

    const {id} = useParams()
    const navigate = useNavigate();

    const setLoading = useLoadingSwitcher()
    const {data, error} = useFetch(`/competition/${id}?light=true`, setLoading, 1)

    return <>
        <button type="button" className="btn btn-link" onClick={() => navigate("/competition")}>
            &laquo; retour
        </button>
        <div>
            {data ? <>
                    <MakeContent data={data}/>
                </>
                : error && <AxiosError error={error}/>
            }
        </div>
    </>
}

const inscText = (type) => {
    if (type === "FREE") {
        return i18n.t('comp.reg.libres')
    } else if (type === "CLUB_ADMIN") {
        return i18n.t('comp.reg.parLesResponsablesDeClub')
    } else if (type === "ADMIN") {
        return i18n.t('comp.reg.parLesAdministrateursDeLaCompétition')
    } else if (type === "HELLOASSO") {
        return i18n.t('comp.reg.surLaBilletterieHelloasso')
    }

    return ""
}

function MakeContent({data}) {
    const {userinfo} = useAuth()
    const navigate = useNavigate()
    const {t} = useTranslation();

    return <div className="card mb-4">
        <div className="card-header">
            <h2 className="card-title" style={{textAlign: "center"}}>{data.name}</h2>
        </div>
        <div className="card-body">
            <p>{data.description}</p>
            <p><strong>{t('date')}
                :</strong> {t('du')} {new Date(data.date.split('T')[0]).toLocaleDateString()} {t('au')} {new Date(data.toDate.split('T')[0]).toLocaleDateString()}
            </p>
            <p><strong>{t('lieu')} :</strong> {data.adresse}</p>
            <p><strong>{t('comp.organisateur')} :</strong> {data.clubName}</p>
            <p><strong>{t('comp.typeDinscription')} :</strong> {inscText(data.registerMode)}</p>
            {(data.registerMode === "FREE" || data.registerMode === "CLUB_ADMIN") &&
                <p><strong>{t('comp.dateDinscription')}
                    :</strong> {t('du')} {new Date(data.startRegister.split('+')[0]).toLocaleString()} {t('au')} {new Date(data.endRegister.split('+')[0]).toLocaleString()}
                </p>
            }

            {(data.registerMode === "FREE" || data.registerMode === "CLUB_ADMIN") && isClubAdmin(userinfo) &&
                <button type="button" className="btn btn-primary"
                        disabled={new Date() < new Date(data.startRegister.split('+')[0]) || new Date() > new Date(data.endRegister.split('+')[0])}
                        onClick={_ => navigate("/competition/" + data.id + "/club/register")}>{t('comp.inscription')}</button>
            }
            {data.registerMode === "FREE" && !isClubAdmin(userinfo) && <SelfRegister data2={data}/>
                || <ShowRegister data2={data}/>
            }
            {data.registerMode === "HELLOASSO" &&
                <p><strong>{t('comp.billetterie')} :</strong> <a
                    href={`https://www.helloasso.com/associations/${data.data1}/evenements/${data.data2}`} target="_blank"
                    rel="noopener noreferrer">{`https://www.helloasso.com/associations/${data.data1}/evenements/${data.data2}`}</a></p>
            }
            {data.canEditRegisters &&
                <div style={{marginTop: "0.5em"}}>
                    <button type="button" className="btn btn-primary"
                            onClick={_ => navigate("/competition/" + data.id + "/register")}>{t('comp.inscriptionModeAdministrateur')}
                    </button>
                </div>
            }
        </div>
    </div>
}

function SelfRegister({data2}) {
    const {id} = useParams()
    const setLoading = useLoadingSwitcher()
    const {data, refresh, error} = useFetch(`/competition/${id}/register/user`, setLoading, 1)
    const {data: data3, error: error2} = useFetch(`/competition/${id}/categories`, setLoading, 1)
    const {t} = useTranslation();

    const [weight, setWeight] = useState("")
    const [cat, setCat] = useState(0)
    const [categories, setCategories] = useState([])

    useEffect(() => {
        if (data && data.length > 0) {
            setWeight(data[0].weight || "")
            setCat(data[0].overCategory || 0)
            setCategories(data[0].categoriesInscrites || [])
        }
    }, [data]);

    const disabled = new Date() < new Date(data2.startRegister.split('+')[0]) || new Date() > new Date(data2.endRegister.split('+')[0])

    const handleUnregister = () => {
        if (window.confirm(t('comp.warn4'))) {
            toast.promise(apiAxios.delete(`/competition/${id}/register/${data[0].id}/user`), getToastMessage("comp.toast.register.self.del")
            ).finally(() => {
                refresh(`/competition/${id}/register/user`)
            })
        }
    }

    const sendSubmit = (new_state) => {
        toast.promise(apiAxios.post(`/competition/${id}/register/user`, new_state), getToastMessage("comp.toast.register.self.add")
        ).finally(() => {
            refresh(`/competition/${id}/register/user`)
        })
    }

    const handleSubmit = () => {
        sendSubmit({
            licence: 0, fname: "", lname: "", weight: weight, overCategory: cat, lockEdit: false, id: null, categoriesInscrites: categories
        })
    }

    const setCategories_ = (e, catId) => {
        if (e.target.checked) {
            if (!categories.includes(catId)) {
                setCategories([...categories, catId])
            }
        } else {
            setCategories(categories.filter(c => c !== catId))
        }
    }

    const currenCat = data?.length > 0 && data[0]?.categorie !== "" ? applyOverCategory(data[0]?.categorie, cat) : "";
    const availableCats = data3 ? (currenCat !== "" ? data3.filter(c => c.categories.some(c2 => c2.categorie === currenCat)) : data3).sort((a, b) => a.name.localeCompare(b.name)) : []

    return <>
        {data
            ? data.length > 0
                ? <div style={{textAlign: "right", maxWidth: "30em"}}>
                    <h4 style={{textAlign: "left"}}>{t('comp.monInscription')}</h4>
                    <div className="input-group mb-3" hidden={!(data2?.requiredWeight.includes(currenCat))}>
                        <span className="input-group-text" id="weight">{t("comp.modal.poids")}</span>
                        <input type="number" min={1} step={0.1} className="form-control" placeholder="--" aria-label="weight" disabled={disabled}
                               name="weight" aria-describedby="weight" value={weight} onChange={e => setWeight(e.target.value)}/>
                        {data[0]?.weightReal && <>
                            <span className="input-group-text" id="weight">{t("comp.modal.pesé")}</span>
                            <input type="number" min={1} step={0.1} className="form-control" placeholder="--" aria-label="weight" disabled={true}
                                   name="weight" aria-describedby="weight" value={data[0]?.weightReal} onChange={() => {
                            }}/>
                        </>}
                    </div>

                    <div style={{textAlign: "left"}}>{t('comp.catégorieNormalisée')}: {getCatName(data[0].categorie)}</div>
                    <div className="input-group mb-3">
                        <span className="input-group-text" id="categorie">{t("comp.modal.surclassement")}</span>
                        <select className="form-select" aria-label="categorie" name="categorie" value={cat} disabled={disabled}
                                onChange={e => setCat(Number(e.target.value))}>
                            <option value={0}>{t('aucun')}</option>
                            <option value={1}>{t('1Catégorie')}</option>
                            <option value={2}>{t('2Catégorie')}</option>
                        </select>
                    </div>

                    <div className="d-flex flex-wrap mb-3">
                        <label htmlFor="inputState2" className="form-label  align-self-center" style={{margin: "0 0.5em 0 0"}}>
                            {t('catégorie')} :
                        </label>
                        {error2 ? <AxiosError error={error2}/> : <>
                            {availableCats && availableCats.length === 0 && <div>{t('aucuneCatégorieDisponible')}</div>}
                            {availableCats && availableCats.map((cat, index) =>
                                <div key={cat.id} className="input-group"
                                     style={{display: "contents"}}>
                                    <div className="input-group-text">
                                        <input className="form-check-input mt-0" type="checkbox"
                                               id={"categoriesInput" + index} checked={categories.includes(cat.id)} aria-label={cat.name}
                                               onChange={e => setCategories_(e, cat.id)}/>
                                        <label style={{marginLeft: "0.5em"}} htmlFor={"categoriesInput" + index}>{cat.name}</label>
                                    </div>
                                </div>)}
                        </>}
                    </div>

                    <div>
                        <button type="button" className="btn btn-danger" disabled={disabled} style={{marginRight: "0.5em"}}
                                onClick={handleUnregister}>{t('button.seDésinscrire')}
                        </button>
                        <button type="button" className="btn btn-primary" disabled={disabled}
                                onClick={handleSubmit}>{t('button.enregistrer')}
                        </button>
                    </div>
                </div>
                : <button type="button" className="btn btn-primary" disabled={disabled} onClick={handleSubmit}>{t('comp.sinscrire')}</button>
            : error
                ? <AxiosError error={error}/>
                : <Def/>
        }
    </>
}

function ShowRegister({data2}) {
    const {id} = useParams()
    const setLoading = useLoadingSwitcher()
    const {data, error} = useFetch(`/competition/${id}/register/user`, setLoading, 1)
    const {data: data3, error: error2} = useFetch(`/competition/${id}/categories`, setLoading, 1)
    const {t} = useTranslation();

    const currenCat = data?.length > 0 && data[0]?.categorie !== "" ? applyOverCategory(data[0]?.categorie, data[0].overCategory) : "";

    return <>
        {data ? data.length > 0
                ? <div style={{textAlign: "right", maxWidth: "30em"}}>
                    <h4 style={{textAlign: "left"}}>{t('comp.monInscription')}</h4>
                    <div style={{textAlign: "left"}}>{t('comp.catégorieNormalisée')} : {getCatName(data[0].categorie)}</div>
                    <div style={{textAlign: "left"}}>{t('comp.modal.surclassement')} :
                        {data[0].overCategory === 0 && ` ${t('aucun')}`}
                        {data[0].overCategory === 1 && ` ${t('1Catégorie')}`}
                        {data[0].overCategory === 2 && ` ${t('2Catégorie')}`}
                    </div>
                    {data2?.requiredWeight.includes(currenCat) &&
                        <div style={{textAlign: "left"}}>{t("comp.modal.poids")} : {data[0].weight} {data[0]?.weightReal && <>
                            ({t("comp.modal.pesé")} : {data[0]?.weightReal})</>}</div>}

                    <div style={{textAlign: "left"}}>{t('catégorie')} :
                        {error2 ? <AxiosError error={error2}/> : <>
                            {data3 && data3.length === 0 && <div>{t('aucuneCatégorieDisponible')}</div>}
                            {data3 && data3.filter(c => data[0].categoriesInscrites.includes(c.id)).sort((a, b) => a.name.localeCompare(b.name)).map(cat =>
                                <span key={cat.id} className="badge text-bg-secondary" style={{margin: "0 0.25em"}}>{cat.name}</span>)}
                        </>}
                    </div>
                </div> : <span>{t('vousNêtesPasEncoreInscrit')}</span>
            : error
                ? <AxiosError error={error}/>
                : <Def/>
        }
    </>
}

function Def() {
    return <div className="list-group">
        <li className="list-group-item"><ThreeDots/></li>
    </div>
}
