import {LoadingProvider, useLoadingSwitcher} from "../hooks/useLoading.jsx";
import {AxiosError} from "../components/AxiosError.jsx";
import {useFetch} from "../hooks/useFetch.js";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {
    faCalendarDay,
    faEnvelope, faFilePdf, faFlag,
    faInfoCircle,
    faMars,
    faMarsAndVenus,
    faUser,
    faUserGroup,
    faVenus
} from "@fortawesome/free-solid-svg-icons";
import {toast} from "react-toastify";
import {apiAxios, getCatName, getToastMessage} from "../utils/Tools.js";
import {useEffect, useState} from "react";
import {useTranslation} from "react-i18next";

const vite_url = import.meta.env.VITE_URL;

export function MePage() {
    const setLoading = useLoadingSwitcher()
    const {data, error} = useFetch(`/member/me`, setLoading, 1)
    const {t} = useTranslation();

    return <div>
        <h1>{t("nav.space")}</h1>

        {data
            ? <div>
                <div className="row">
                    <div className="col-lg-4">
                        <PhotoCard data={data}/>
                    </div>
                    <div className="col-lg-8">
                        <InformationForm data={data}/>
                        <SettingsCard data={data}/>
                        <div className="row">
                            <div className="col-md-6">
                                <LoadingProvider><LicenceCard userData={data}/></LoadingProvider>
                            </div>
                            <div className="col-md-6">
                                <LoadingProvider><SelectCard userData={data}/></LoadingProvider>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            : error && <AxiosError error={error}/>
        }
    </div>
}

export function LicenceCard({userData}) {
    const {t} = useTranslation();

    return <div className="card mb-4 mb-md-0">
        <div className="card-header container-fluid">
            <div className="row">
                <div className="col">{t('licence')}</div>
            </div>
        </div>
        <div className="card-body">
            <ul className="list-group">
                {userData.licences.map((licence, index) => {
                    return <div key={index}
                                className={"list-group-item d-flex justify-content-between align-items-start list-group-item-" +
                                    (licence.validate ? "success" : (licence.certificate ? "warning" : "danger"))}>
                        <div className="me-auto">{licence?.saison}-{licence?.saison + 1}</div>
                    </div>
                })}
            </ul>
        </div>
    </div>;
}

function PhotoCard({data}) {
    const {t} = useTranslation();

    return <div className="card mb-4">
        <div className="card-header">{t("licenceNo", {no: data.licence})}</div>
        <div className="card-body text-center">
            <div className="input-group mb-3">
                <img
                    src={`${vite_url}/api/member/me/photo`}
                    alt="avatar"
                    className="rounded-circle img-fluid" style={{object_fit: 'contain'}}/>
            </div>

            <a href={`${vite_url}/api/member/me/licence`} target='#'>
                <button className="btn btn-primary" type="button" id="button-addon1"
                        onClick={() => null}>
                    {t('téléchargéeLaLicence')} <FontAwesomeIcon icon={faFilePdf}></FontAwesomeIcon>
                </button>
            </a>
        </div>
    </div>;
}

function SelectCard({userData}) {
    const {t} = useTranslation();

    return <div className="card mb-4 mb-md-0">
        <div className="card-header">{t('sélectionEnéquipeDeFrance')}</div>
        <div className="card-body">
            <ul className="list-group">
                {userData?.selections && userData.selections.sort((a, b) => b.saison - a.saison).map((selection, index) => {
                    return <div key={index} className="list-group-item d-flex justify-content-between align-items-start">
                        <div className="me-auto">{selection?.saison}-{selection?.saison + 1} {t('en')} {getCatName(selection?.categorie)}</div>
                    </div>
                })}
            </ul>
        </div>
    </div>;
}

function SettingsCard({data}) {
    const [privacy, setPrivacy] = useState("PUBLIC");
    const {t} = useTranslation();

    useEffect(() => {
        if (data?.resultPrivacy) {
            setPrivacy(data.resultPrivacy);
        }
    }, [data]);

    const handleChange = (e) => {
        const formData = new FormData();
        formData.append("resultPrivacy", e.target.value);
        toast.promise(apiAxios.put(`/member/me/setting`, formData), getToastMessage("me.toast.settings"))
            .then(() => {
                setPrivacy(String(formData.get("resultPrivacy")));
            });
    }

    return <div className="card mb-4">
        <div className="card-header">{t('me.paramètresDuCompte')}</div>
        <div className="card-body">
            <div className="input-group mb-3">
                <label className="input-group-text" htmlFor="email_notifications">{t('me.visibilitéDesRésultats')}</label>
                <select className="form-select" id="result_visibility" name="result_visibility" required value={privacy} onChange={handleChange}>
                    <option value="PUBLIC">{t('me.result.PUBLIC')}</option>
                    <option value="REGISTERED_ONLY">{t('me.result.REGISTERED_ONLY')}</option>
                    <option value="REGISTERED_ONLY_NO_DETAILS">{t('me.result.REGISTERED_ONLY_NO_DETAILS')}</option>
                    <option value="PRIVATE">{t('me.result.PRIVATE')}</option>
                </select>
            </div>
        </div>
    </div>;
}

function InformationForm({data}) {
    const style = {marginRight: '0.7em'}
    const {t} = useTranslation();

    return <div className="card mb-4">
        <div className="card-header">{t('information')}</div>
        <div className="card-body">
            <div className="row mb-2">
                <p>
                    <FontAwesomeIcon icon={faUser} style={style}/>{data.lname} {data.fname}<br/>
                    <FontAwesomeIcon icon={faEnvelope} style={style}/>{data.email}<br/>
                    {data.genre === 'Homme' && <FontAwesomeIcon icon={faMars} style={style}/>
                        || data.genre === 'Femme' && <FontAwesomeIcon icon={faVenus} style={style}/>
                        || <FontAwesomeIcon icon={faMarsAndVenus} style={style}/>}{data.genre}<br/>
                    <FontAwesomeIcon icon={faCalendarDay} style={style}/>{data.birth_date ? data.birth_date.split('T')[0] : ''}<br/>
                    <FontAwesomeIcon icon={faUserGroup} style={style}/>{data.categorie}<br/>
                    <FontAwesomeIcon icon={faFlag} style={style}/>{t('nationalité')} : <img src={"/flags/flags_" + data.country.toLowerCase() + ".png"}
                                                                                     alt=""/><br/>
                    <FontAwesomeIcon icon={faInfoCircle} style={style}/>{t("club", {count: 1})} : {data.club}<br/>
                    <FontAwesomeIcon icon={faInfoCircle} style={style}/>{t('me.rôleAuSienDuClub')} : {data.role}<br/>
                    <FontAwesomeIcon icon={faInfoCircle} style={style}/>{t('me.formationDarbitrage')} : {data.grade_arbitrage}
                </p>
                <div>
                    <button className="btn btn-primary" type="button" id="button-addon1"
                            onClick={_ => window.location.href = "https://auth.ffsaf.fr/realms/ffsaf/login-actions/reset-credentials?client_id=ffsaf-client"}>
                        {t('me.changerMonMotDePasse')}
                    </button>
                </div>
            </div>
        </div>
    </div>;
}
