import {useNavigate, useParams} from "react-router-dom";
import {LoadingProvider, useLoadingSwitcher} from "../../../hooks/useLoading.jsx";
import {useFetch} from "../../../hooks/useFetch.js";
import {AxiosError} from "../../../components/AxiosError.jsx";
import {toast} from "react-toastify";
import {apiAxios, errFormater, getToastMessage} from "../../../utils/Tools.js";
import {RoleList, TextField} from "../../../components/MemberCustomFiels.jsx";
import {useEffect, useRef, useState} from "react";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faFilePdf} from "@fortawesome/free-solid-svg-icons";
import {useTranslation} from "react-i18next";

const vite_url = import.meta.env.VITE_URL;

export function AffiliationReqPage() {
    const {id} = useParams()
    const navigate = useNavigate();
    const {t} = useTranslation();

    const setLoading = useLoadingSwitcher()
    const {data, refresh, error} = useFetch(`/affiliation/request/${id}`, setLoading, 1)

    return <>
        <h2>{t("nav.aff_request")}</h2>
        <button type="button" className="btn btn-link" onClick={() => navigate("/admin/club")}>
            {t('back')}
        </button>
        <div>
            {data
                ? <div className="">
                    <Content data={data} refresh={refresh}/>
                </div>
                : error && <AxiosError error={error}/>
            }
        </div>
    </>
}

function Content({data, refresh}) {
    const navigate = useNavigate();
    const {t} = useTranslation();

    const handleRm = (reason) => {
        toast.promise(
            apiAxios.delete(`/affiliation/request/${data.id}?reason=${encodeURIComponent(reason)}`), getToastMessage('aff.toast.del')
        ).then(_ => {
            navigate("/admin/affiliation/request")
        })
    }

    const handleSubmit = (event) => {
        event.preventDefault();

        if (event.nativeEvent.submitter.value === "rm") {
            return;
        }

        const formData = new FormData();
        let err = 0;

        formData.append('id', data.id);
        formData.append('name', event.target.name.value);
        formData.append('state_id', event.target.state_id.value);
        formData.append('address', event.target.address.value);
        formData.append('contact', event.target.contact.value);

        if (event.target.logo.files[0])
            formData.append('logo', event.target.logo.files[0]);
        if (event.target.status.files[0])
            formData.append('status', event.target.status.files[0]);

        for (let i = 0; i < 3; i++) {
            const mode = event.target['mode' + i].value;

            formData.append(`m${i + 1}_mode`, mode);
            formData.append(`m${i + 1}_role`, event.target['role' + i].value);

            if (mode === '0') {
                if (event.target['mode0_licence' + i].value === "") {
                    toast.error(t('aff.submit.error1', {id: i + 1}));
                    err++;
                    continue;
                }

                formData.append(`m${i + 1}_licence`, event.target['licence' + i].value);
            } else if (mode === '1') {
                if (event.target['similar' + i].value === -1) {
                    toast.error(t('aff.submit.error2', {id: i + 1}));
                    err++;
                    continue;
                }

                formData.append(`m${i + 1}_licence`, event.target['mode1_licence' + i].value);
            } else {
                formData.append(`m${i + 1}_lname`, event.target['lname' + i].value);
                formData.append(`m${i + 1}_fname`, event.target['fname' + i].value);
            }

            if (event.target['flexRadioDefault' + i].value === '0') {
                if (event.target['new_email' + i].value === "") {
                    toast.error(t('aff.submit.error3', {id: i + 1}));
                    err++;
                    continue;
                }

                formData.append(`m${i + 1}_email`, event.target['new_email' + i].value);
            } else {
                if (event.target['old_email' + i].value === "") {
                    toast.error(t('aff.submit.error3', {id: i + 1}));
                    err++;
                    continue;
                }

                formData.append(`m${i + 1}_email`, event.target['old_email' + i].value);
            }
            formData.append(`m${i + 1}_email_mode`, event.target['flexRadioDefault' + i].value);
        }

        if (err > 0)
            return;

        if (event.nativeEvent.submitter.value === "save") {
            toast.promise(apiAxios.put(`/affiliation/request/save`, formData), getToastMessage('aff.toast.save')
            ).then(_ => {
                refresh(`/affiliation/request/${data.id}`)
            })
        } else if (event.nativeEvent.submitter.value === "accept") {
            toast.promise(
                apiAxios.put(`/affiliation/request/apply`, formData), getToastMessage('aff.toast.accept')
            ).then(_ => {
                navigate("/admin/affiliation/request")
            })
        }
    }

    return <>
        <form onSubmit={handleSubmit}>
            <div className="card mb-4">
                <input name="id" value={data.id} readOnly hidden/>
                <div className="card-header">{t("nav.aff_request")}</div>
                <div className="card-body text-center">
                    {data.club && <h5>{t('aff.info1', {no: data.club_no_aff})}</h5>}
                    <h4 id="saison">{t('saison')} {data.saison}-{data.saison + 1}</h4>

                    <div className="row mb-3">
                        <div className="input-group">
                            <span className="input-group-text" id="name">{t('aff.nomDuClub')}</span>
                            <input type="text" className="form-control" placeholder={t('aff.nomDuClub')} aria-label="name"
                                   name="name" aria-describedby="name" defaultValue={data.name} required/>
                        </div>
                        {data.club && <div className="form-text" id="name">{t('aff.ancienNom', {name: data.club_name})}</div>}
                    </div>

                    <TextField name="state_id" text={t('siretOuRna')} value={data.stateId} disabled={true}/>
                    <TextField name="address" text={t('adresse')} value={data.address}/>
                    <TextField name="contact" text={t('contactAdministratif')} value={data.contact}/>

                    <img
                        src={`${vite_url}/api/affiliation/request/${data.id}/logo`}
                        alt="avatar"
                        className="img-fluid" style={{object_fit: 'contain', maxHeight: '15em'}}/>
                    <div className="mb-3">
                        <div className="input-group">
                            <label className="input-group-text" htmlFor="logo">{t('blason')}</label>
                            <input type="file" className="form-control" id="logo" name="logo"
                                   accept=".jpg,.jpeg,.gif,.png,.svg"/>
                        </div>
                        <div className="form-text" id="logo">{t('keepEmpty')}</div>
                    </div>
                    <div className="mb-3">
                        <div className="input-group">
                            <label className="input-group-text" htmlFor="status">{t('status')}</label>
                            <a href={`${vite_url}/api/affiliation/request/${data.id}/status`} target='_blank'>
                                <button className="btn btn-outline-secondary" type="button" id="button-addon1"
                                        onClick={_ => null}><FontAwesomeIcon icon={faFilePdf}></FontAwesomeIcon>
                                </button>
                            </a>
                            <input type="file" className="form-control" id="status" name="status" accept=".pdf,.txt"/>
                        </div>
                        <div className="form-text" id="status">{t('keepEmpty')}</div>
                    </div>

                    {data.members.map((member, index) => {
                        return <div key={index} className="row">
                            <MemberPart index={index} member={member}/>
                        </div>
                    })}

                </div>
                <div className="row mb-3">
                    <div className="d-grid gap-2 d-md-flex justify-content-md-end">
                        <button type="submit" value="accept" className="btn btn-success">{t('button.accepter')}</button>
                        <button type="submit" value="save" className="btn btn-primary">{t('button.enregistrer')}</button>
                        <button className="btn btn-danger" value="rm" data-bs-toggle="modal"
                                data-bs-target="#confirm-delete">{t('button.refuser')}</button>
                        <ConfirmReasonDialog title={t('aff.refuserLaDemande')} message={t('aff.refuserLaDemande.detail')}
                                             onConfirm={handleRm}/>
                    </div>
                </div>
            </div>
        </form>
    </>
}

function ConfirmReasonDialog({onConfirm, id = "confirm-delete"}) {
    const [reason, setReason] = useState("")
    const {t} = useTranslation();

    return <div className="modal fade" id={id} tabIndex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div className="modal-dialog">
            <div className="modal-content">
                <div className="modal-header">
                    <h4 className="modal-title" id="myModalLabel">{t('aff.refuserLaDemande')}</h4>
                </div>
                <div className="modal-body">
                    <div className="row mb-3">
                        <div className="col">
                            <label htmlFor="reason" className="form-label">{t('aff.raisonDuRefus')}</label>
                            <textarea className="form-control" id="reason" name="reason" rows="3"
                                      placeholder={t('aff.raisonDuRefus.msg')} value={reason}
                                      onChange={e => setReason(e.target.value)}></textarea>
                        </div>
                    </div>
                    <span>{t('aff.refusConfirm')}</span>
                </div>
                <div className="modal-footer">
                    <button type="button" className="btn btn-default" data-dismiss="modal" data-bs-dismiss="modal">{t('button.annuler')}</button>
                    <a className="btn btn-danger btn-ok" data-bs-dismiss="modal" onClick={_ => onConfirm(reason)}>{t('button.confirmer')}</a>
                </div>
            </div>
        </div>
    </div>
}

function MemberPart({index, member}) {
    const [mode, setMode] = useState(member.licence >= 0 ? 0 : 2)
    const [current, setCurrent] = useState(-1)
    const [email, setEmail] = useState("")
    const [emailChoice, setEmailChoice] = useState("0")
    const {t} = useTranslation();

    useEffect(() => {
        if (mode !== 1)
            setCurrent(-1)
        if (mode === 2) {
            setEmail("")
        }
    }, [mode]);


    return <div className="col mb-4">
        <div className="card">
            <div className="card-header">{t('aff.membreNo', {no: index + 1})}</div>
            <input name={"mode" + index} value={mode} readOnly hidden/>
            <div className="card-body">
                <RoleList name={"role" + index} text={t('role')} value={member.role}/>

                <div className="btn-group row" role="group">
                    <div className="mb-2">
                        <div className="card">
                            <div className="card-header">
                                <input type="radio" className="btn-check" id={"btnradio1" + index} autoComplete="off"
                                       checked={mode === 0} onChange={() => setMode(0)}/>
                                <label className="btn btn-outline-primary" htmlFor={"btnradio1" + index}>{t('aff.byNoLicence')}</label>
                            </div>

                            <div className="card-body">
                                <LoadingProvider>
                                    <MemberLicence member={member} mode={mode} index={index} setEmail={setEmail}/>
                                </LoadingProvider>
                            </div>
                        </div>
                    </div>

                    <div className="col-lg-5 mb-2">
                        <div className="card">
                            <div className="card-header">
                                <input type="radio" className="btn-check" id={"btnradio2" + index} autoComplete="off"
                                       checked={mode === 1} onChange={() => setMode(1)}/>
                                <label className="btn btn-outline-primary" htmlFor={"btnradio2" + index}>{t('aff.byMembreSim')}</label>
                            </div>
                            <div className="card-body">
                                <input name={"similar" + index} value={current} readOnly hidden/>
                                <LoadingProvider>
                                    <MemberSimilar member={member} mode={mode} current={current} setCurrent={setCurrent} index={index}
                                                   setEmail={setEmail}/>
                                </LoadingProvider>
                            </div>
                        </div>
                    </div>

                    <div className="col mb-2">
                        <div className="card">
                            <div className="card-header">
                                <input type="radio" className="btn-check" id={"btnradio3" + index} autoComplete="off"
                                       checked={mode === 2} onChange={() => setMode(2)}/>
                                <label className="btn btn-outline-primary" htmlFor={"btnradio3" + index}>{t('aff.byNewMenbre')}</label>
                            </div>
                            <div className="card-body">
                                <TextField name={"lname" + index} text={t('nom')} value={member.lname} disabled={mode !== 2}/>
                                <TextField name={"fname" + index} text={t('prenom')} value={member.fname} disabled={mode !== 2}/>
                            </div>
                        </div>
                    </div>
                </div>

                <div className="input-group">
                    <div className="input-group-text">
                        <input className="form-check-input mt-0" type="radio" value="0" aria-label={t('nouvelEmail')}
                               name={"flexRadioDefault" + index} checked={emailChoice === '0'}
                               onChange={e => setEmailChoice(e.target.value)}/>
                    </div>
                    <span className="input-group-text">{t('nouvelEmail')}</span>
                    <input type="Email" className="form-control" aria-label={t('nouvelEmail')} defaultValue={member.email}
                           name={"new_email" + index} autoComplete="false"/>
                </div>
                <div className="input-group">
                    <div className="input-group-text">
                        <input className="form-check-input mt-0" type="radio" value="1" aria-label="ancien email"
                               name={"flexRadioDefault" + index} disabled={!email} checked={emailChoice === '1'}
                               onChange={e => setEmailChoice(e.target.value)}/>
                    </div>
                    <span className="input-group-text">{t('conserverLancienEmail')}</span>
                    <input type="Email" className="form-control" aria-label="ancien email" disabled={true}
                           name={"old_email" + index} value={email} autoComplete="false"/>
                </div>
            </div>
        </div>
    </div>
}

function MemberLicence({member, mode, index, setEmail}) {
    const setLoading = useLoadingSwitcher()
    const [licence, setLicence] = useState(member.licence)
    const {data, refresh} = useFetch(null, setLoading, 1)
    const ref = useRef(-1)
    const {t} = useTranslation();

    useEffect(() => {
        if (licence === -1 || licence.length < 1 || licence === ref.current)
            return
        refresh(`/member/find/licence?id=${licence}`)
        ref.current = licence
    }, [licence]);


    useEffect(() => {
        if (data && mode === 0) {
            if (data)
                setEmail(data.email)
            else
                setEmail("")
        } else if (mode === 0)
            setEmail("")
    }, [data, mode]);

    const name = "licence" + index;
    return <>
        <input name={"mode0_licence" + index} value={data ? data.licence : ""} readOnly hidden/>
        <div className="row">
            <div className="input-group mb-3">
                <span className="input-group-text" id={name}>{t('licence')}</span>
                <input type="text" className="form-control" placeholder="00000" name={name}
                       value={licence >= 0 ? String(licence) : ""} disabled={mode !== 0} required={mode === 0}
                       onChange={event => setLicence(event.target.value)}/>
            </div>
        </div>
        {data && <span
            className="form-text">{t('nom')}: {data.lname} {data.fname}, {t('club', {count: 1})}: {data.club ? data.club.name : t('club', {count: 0})}</span>}
    </>
}

function MemberSimilar({member, current, setCurrent, mode, index, setEmail}) {
    const setLoading = useLoadingSwitcher()
    const {data} = useFetch(`/member/find/similar?fname=${encodeURI(member.fname)}&lname=${encodeURI(member.lname)}`, setLoading, 1)
    const {t} = useTranslation();

    useEffect(() => {
        if (data && current >= 0 && mode === 1) {
            if (data[current])
                setEmail(data[current].email)
            else
                setEmail("")
        } else if (mode === 1)
            setEmail("")
    }, [current, data, mode]);

    return <div className="list-group">
        <input name={"mode1_licence" + index} value={(current >= 0) ? data[current].licence : ""} readOnly hidden/>
        {data && data.map((m, index) => {
            return <button key={index} type="button" aria-current={current === index}
                           className={"list-group-item list-group-item-action" + (current === index ? " active" : "")}
                           onClick={() => setCurrent(index)} disabled={mode !== 1}>
                {m.lname} {m.fname}<br/>
                <small>{m.club ? m.club.name : t('club', {count: 0})}</small>
            </button>
        })}
    </div>
}
