import {useEffect, useState} from "react";
import {apiAxios, getToastMessage} from "../utils/Tools.js";
import {toast} from "react-toastify";
import {useLocation, useNavigate} from "react-router-dom";
import {useTranslation} from "react-i18next";

const notUpperCase = ["de", "la", "le", "les", "des", "du", "d'", "l'", "sur", 'lieu', 'dit'];

function formatAdresse(data) {
    const words = data.split(" ");

    return words.map((word) => {
        if (notUpperCase.includes(word.toLowerCase())) {
            return word.toLowerCase();
        }
        return word[0].toUpperCase() + word.substring(1).toLowerCase();
    }).join(" ");
}

function reconstruireAdresse2(infos) {
    let adresseReconstruite = "";

    if (infos?.complement)
        adresseReconstruite += formatAdresse(infos.complement) + ', ';

    adresseReconstruite += formatAdresse(infos.voie) + ', ';
    adresseReconstruite += infos.code_postal + ' ' + infos.commune.nom + ', ';

    if (infos?.pays)
        adresseReconstruite += formatAdresse(infos.pays) + ', ';

    if (adresseReconstruite.endsWith(', ')) {
        adresseReconstruite = adresseReconstruite.slice(0, -2);
    }

    return adresseReconstruite;
}

function getSaisonToAff(currentDate = new Date()) {
    if (currentDate.getMonth() >= 7) { //aout et plus
        return currentDate.getFullYear()
    } else {
        return currentDate.getFullYear() - 1
    }
}

export function DemandeAff() {
    const {hash} = useLocation();
    const navigate = useNavigate();
    const [initData, setInitData] = useState(null)
    const [needFile, setNeedFile] = useState(true)
    const {t} = useTranslation();

    useEffect(() => {
        if (hash.startsWith("#d")) {
            const data = JSON.parse(decodeURI(hash.substring(2)));
            setInitData(data)
            setNeedFile(false)
        } else if (hash.startsWith("#e")) {
            apiAxios.get(`/affiliation/request/${hash.substring(2)}`).then(data => {
                for (let i = 0; i < data.data.members.length; i++) {
                    if (data.data.members[i].licence === -1)
                        data.data.members[i].licence = ""
                }
                setInitData(data.data)
                setNeedFile(false)
            }).catch(_ => {
                setInitData({})
            })
        } else {
            setInitData({})
        }
    }, []);

    const submit = (event) => {
        event.preventDefault()
        const formData = new FormData(event.target)
        formData.append("m1_role", event.target.m1_role?.value)
        formData.append("state_id", event.target.state_id?.value)

        let error = false;
        for (let i = 1; i <= 3; i++) {
            if (event.target[`m${i}_role`]?.value === "0") {
                toast.error(t('aff_req.error1', {i: i}));
                error = true;
            }
        }
        if (error) {
            return;
        }

        if (event.nativeEvent.submitter.value === "undo") {
            toast.promise(
                apiAxios.delete(`/affiliation/request/${initData.id}`), getToastMessage('aff_req.toast.undo')
            ).then(_ => {
                navigate("/club/me")
            })
        } else if (event.nativeEvent.submitter.value === "edit") {
            formData.append("id", initData.id)

            toast.promise(
                apiAxios.put(`/affiliation/request/edit`, formData), getToastMessage('toast.edit')
            ).then(_ => {
                navigate("/club/me")
            })
        } else {
            formData.append("id", -1)

            toast.promise(
                apiAxios.post(`/affiliation/request`, formData, {headers: {'Accept': '*/*'}}), getToastMessage('aff.toast.save')
            ).then(_ => {
                navigate("/affiliation/ok")
            })
        }
    }

    return <div>
        <h1>{t("nav.aff_request")} {getSaisonToAff() + "-" + (getSaisonToAff() + 1)}</h1>
        <p>{t('aff_req.text1')}</p>
        {t('aff_req.text2')}
        <ul>
            {t('aff_req.text2.li', {returnObjects: true}).map((text, index) => <li key={index}>{text}</li>)}
        </ul>

        {initData && <div className="card mb-4">
            <form onSubmit={submit}>
                <div className="card-body">
                    <h4>{t('aff_req.association')}</h4>
                    <AssoInfo initData={initData} needFile={needFile}/>
                    <h4>{t("aff.membreNo", {no: 1})}</h4>
                    <MembreInfo role="m1" initData={initData.members?.at(0) || {}}/>
                    <h4 style={{marginTop: '1em'}}>{t("aff.membreNo", {no: 2})}</h4>
                    <MembreInfo role="m2" initData={initData.members?.at(1) || {}}/>
                    <h4 style={{marginTop: '1em'}}>{t("aff.membreNo", {no: 3})}</h4>
                    <MembreInfo role="m3" initData={initData.members?.at(2) || {}}/>

                    <div className="mb-3" style={{marginTop: '1em'}}>
                        {!initData.id && <p>{t('aff_req.text3')}</p>}
                        {t('aff_req.text4')}
                        <ul>
                            <li>{t('aff_req.text4.li1')}</li>
                            <li>{t('aff_req.text4.li2')}</li>
                        </ul>
                    </div>

                    {!initData.id ?
                        <div className="row">
                            <div className="d-grid gap-2 d-md-flex justify-content-md-center">
                                <button type="submit" value="new" className="btn btn-primary">{t('aff_req.button.confirm')}</button>
                            </div>
                        </div> :
                        <div className="row">
                            <div className="d-grid gap-2 d-md-flex justify-content-md-center col">
                                <button type="submit" value="undo" className="btn btn-danger">{t('aff_req.button.cancel')}</button>
                            </div>
                            <div className="d-grid gap-2 d-md-flex justify-content-md-center col">
                                <button type="submit" value="edit" className="btn btn-primary">{t('aff_req.button.save')}</button>
                            </div>
                        </div>
                    }
                </div>
            </form>
        </div>}
    </div>
}

function AssoInfo({initData, needFile}) {
    const [denomination, setDenomination] = useState("")
    const [stateId, setStateId] = useState(initData.stateId ? String(initData.stateId) : (initData.state_id ? String(initData.state_id) : ""))
    const [adresse, setAdresse] = useState(initData.address ? initData.address : "")
    const [contact, setContact] = useState(initData.contact ? initData.contact : "")
    const {t} = useTranslation();

    const fetchStateId = () => {
        const regex = /^(?:\d{14}|W\d{9})$/;
        let sid = stateId;
        if (!regex.test(stateId)) {
            toast.error(t('aff_req.error2'));
            return;
        } else {
            if (stateId[0] !== 'W')
                sid = stateId.substring(0, 9); // Pour les SIRET, on ne garde que les 9 premiers chiffres (SIREN)
        }

        toast.promise(
            apiAxios.get(`asso/state_id/${sid}`), getToastMessage("aff_req.toast.search")
        ).then(data => {
            const data2 = data.data
            setDenomination(data2.identite.nom)
            if (!initData.saison || adresse === "")
                setAdresse(reconstruireAdresse2(data2.coordonnees.adresse_gestion))
        })
    }
    return <>
        <input name="saison" value={getSaisonToAff()} readOnly hidden/>

        <div className="input-group mb-3">
            <span className="input-group-text" id="basic-addon1">{t('aff_req.nomDeLassociation')}*</span>
            <input type="text" className="form-control" placeholder={t('aff_req.nomDeLassociation')} name="name"
                   aria-label={t('aff_req.nomDeLassociation')}
                   aria-describedby="basic-addon1" required defaultValue={initData.name ? initData.name : ""}/>
        </div>

        <div className="input-group mb-3">
            <span className="input-group-text">{t('noSiretOuRna')}*</span>
            <input type="text" className="form-control" placeholder={t('noSiretOuRna')} name="state_id" required value={stateId} disabled={!needFile}
                   onChange={e => setStateId(e.target.value)}/>
            <button className="btn btn-outline-secondary" type="button" id="button-addon2"
                    onClick={fetchStateId} hidden={false}>{t('rechercher')}
            </button>
        </div>

        <div className="input-group mb-3" hidden={false}>
            <span className="input-group-text" id="basic-addon1">{t('aff_req.denomination')}</span>
            <input type="text" className="form-control" placeholder={t('aff_req.appuyerSurRechercher')}
                   aria-label={t('aff_req.denomination')}
                   aria-describedby="basic-addon1" disabled value={denomination} readOnly/>
        </div>

        <div className="mb-3">
            <div className="input-group">
                <span className="input-group-text" id="basic-addon1">{t('adresseAdministrative')}*</span>
                <input type="text" className="form-control" placeholder={t('adresseAdministrative')} aria-label={t('adresseAdministrative')}
                       aria-describedby="basic-addon1"
                       required value={adresse} name="adresse" onChange={e => setAdresse(e.target.value)}/>
            </div>
            <div className="form-text" id="adresse">{t('aff_req.text5')}</div>
        </div>

        <div className="mb-3">
            <div className="input-group">
                <span className="input-group-text" id="basic-addon1">{t('contactAdministratif')}*</span>
                <input type="email" className="form-control" placeholder={t('contactAdministratif')} aria-label={t('contactAdministratif')}
                       aria-describedby="basic-addon1"
                       required value={contact} name="contact" onChange={e => setContact(e.target.value)}/>
            </div>
        </div>

        <div className="mb-3">
            <div className="input-group">
                <label className="input-group-text" htmlFor="logo">{t('blason')}{needFile && "*"}</label>
                <input type="file" className="form-control" id="logo" name="logo" accept=".jpg,.jpeg,.gif,.png,.svg"
                       required={needFile}/>
            </div>
            {!needFile && <div className="form-text" id="status">{t('aff_req.text6')}</div>}
        </div>

        <div className="mb-3">
            <div className="input-group">
                <label className="input-group-text" htmlFor="status">{t('statuts')}{needFile && "*"}</label>
                <input type="file" className="form-control" id="status" name="status" accept=".pdf,.txt" required={needFile}/>
            </div>
            {!needFile && <div className="form-text" id="status">{t('aff_req.text7')}</div>}
        </div>
    </>;
}

function MembreInfo({role, initData}) {
    const [switchOn, setSwitchOn] = useState(!!initData.licence);
    const {t} = useTranslation();

    return <>
        <div className="input-group mb-3">
            <label className="input-group-text" htmlFor="inputGroupSelect01">{t('role')}</label>
            <select className="form-select" id="inputGroupSelect01" defaultValue={initData.role ? initData.role : (role === "m1" ? "PRESIDENT" : 0)}
                    disabled={initData.role ? initData.role === "PRESIDENT" : role === "m1"} name={role + "_role"} required>
                <option value="0">{t('selectionner...')}</option>
                <option value="PRESIDENT">{t('role.président')}</option>
                <option value="TRESORIER">{t('role.trésorier')}</option>
                <option value="SECRETAIRE">{t('role.secrétaire')}</option>
                <option value="VPRESIDENT">{t('role.vise-président')}</option>
                <option value="VTRESORIER">{t('role.vise-trésorier')}</option>
                <option value="VSECRETAIRE">{t('role.vise-secrétaire')}</option>
                <option value="MEMBREBUREAU">{t('role.membreDuBureau')}</option>
            </select>
        </div>

        <div className="row g-3 mb-3">
            <div className="col-sm-3">
                <div className="form-floating">
                    <input type="text" className="form-control" id="floatingInput" placeholder={t('nom')} name={role + "_nom"}
                           defaultValue={initData.lname ? initData.lname : ""} required/>
                    <label htmlFor="floatingInput">{t('nom')}*</label>
                </div>
            </div>
            <div className="col-sm-3">
                <div className="form-floating">
                    <input type="text" className="form-control" id="floatingInput" placeholder={t('prenom')}
                           name={role + "_prenom"} defaultValue={initData.fname ? initData.fname : ""} required/>
                    <label htmlFor="floatingInput">{t('prenom')}*</label>
                </div>
            </div>
            <div className="col-sm-5">
                <div className="form-floating">
                    <input type="email" className="form-control" id="floatingInput" placeholder="name@example.com"
                           name={role + "_mail"} defaultValue={initData.email ? initData.email : ""} required/>
                    <label htmlFor="floatingInput">{t('email')}*</label>
                </div>
            </div>
        </div>

        <div className="input-group mb-3">
            <label className="input-group-text" htmlFor="inputGroupSelect01">{t('aff_req.disposeLicence')}</label>
            <div className="input-group-text">
                <input type="checkbox" id="inputGroupSelect01" className="form-check-input mt-0"
                       checked={switchOn} onChange={() => setSwitchOn(!switchOn)}/>
            </div>
        </div>
        {switchOn &&
            <div className="col-sm-3">
                <div className="form-floating">
                    <input type="number" className="form-control" id="floatingInput" placeholder={t('noLicence')}
                           name={role + "_licence"} defaultValue={initData.licence ? Number(initData.licence) : ""} required/>
                    <label htmlFor="floatingInput">{t('noLicence')}</label>
                </div>
            </div>
        }

    </>
}

export function DemandeAffOk() {
    const {t} = useTranslation();

    return (
        <div>
            <h1 className="text-green-800 text-4xl">{t('aff_req.text7')}</h1>
            <p>{t('aff_req.text8')}</p>
        </div>
    );
}
