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} 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";

const vite_url = import.meta.env.VITE_URL;

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

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

    return <>
        <h2>Demande d'affiliation</h2>
        <button type="button" className="btn btn-link" onClick={() => navigate("/admin/affiliation/request")}>
            &laquo; retour
        </button>
        <div>
            {data
                ? <div className="">
                    <Content data={data} refresh={refresh}/>
                </div>
                : error && <AxiosError error={error}/>
            }
        </div>
    </>
}

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

    const handleRm = (reason) => {
        toast.promise(
            apiAxios.delete(`/affiliation/request/${data.id}?reason=${encodeURIComponent(reason)}`),
            {
                pending: "Suppression de la demande d'affiliation en cours",
                success: "Demande d'affiliation supprimée avec succès 🎉",
                error: {
                    render({data}) {
                        return errFormater(data, "Échec de la suppression de la demande d'affiliation")
                    }
                }
            }
        ).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('siret', event.target.siret.value);
        formData.append('rna', event.target.rna.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("Veuillez saisir un numéro de licence valide pour le membre " + (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("Veuillez choisir un membre similaire pour le membre " + (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("Veuillez saisir un email valide pour le membre " + (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("Veuillez saisir un email valide pour le membre " + (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),
                {
                    pending: "Enregistrement de la demande d'affiliation en cours",
                    success: "Demande d'affiliation enregistrée avec succès 🎉",
                    error: {
                        render({data}) {
                            return errFormater(data, "Échec de l'enregistrement de la demande d'affiliation")
                        }
                    }
                }
            ).then(_ => {
                refresh(`/affiliation/request/${data.id}`)
            })
        } else if (event.nativeEvent.submitter.value === "accept") {
            toast.promise(
                apiAxios.put(`/affiliation/request/apply`, formData),
                {
                    pending: "Acceptation de l'affiliation en cours",
                    success: "Affiliation acceptée avec succès 🎉",
                    error: {
                        render({data}) {
                            return errFormater(data, "Échec de l'acceptation de l'affiliation")
                        }
                    }
                }
            ).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">Demande d'affiliation</div>
                <div className="card-body text-center">
                    {data.club && <h5>Ce club a déjà été affilié (affiliation n°{data.club_no_aff})</h5>}
                    <h4 id="saison">Saison {data.saison}-{data.saison + 1}</h4>

                    <div className="row mb-3">
                        <div className="input-group">
                            <span className="input-group-text" id="name">Nom du club</span>
                            <input type="text" className="form-control" placeholder="Nom du club" aria-label="name"
                                   name="name" aria-describedby="name" defaultValue={data.name} required/>
                        </div>
                        {data.club && <div className="form-text" id="name">Ancien nom: {data.club_name}</div>}
                    </div>

                    <TextField type="number" name="siret" text="SIRET" value={data.siret} disabled={true}/>
                    <TextField name="rna" text="RNA" value={data.rna} required={false}/>
                    <TextField name="address" text="Adresse" value={data.address}/>
                    <TextField name="contact" text="Contact administratif" 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">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">Laissez vide pour ne rien changer.</div>
                    </div>
                    <div className="mb-3">
                        <div className="input-group">
                            <label className="input-group-text" htmlFor="status">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">Laissez vide pour ne rien changer.</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">Accepter</button>
                        <button type="submit" value="save" className="btn btn-primary">Enregistrer</button>
                        <button className="btn btn-danger" value="rm" data-bs-toggle="modal" data-bs-target="#confirm-delete">Refuser</button>
                        <ConfirmReasonDialog title="Refuser la demande" message="Êtes-vous sûr de vouloir refuser cette demande ?"
                                             onConfirm={handleRm}/>
                    </div>
                </div>
            </div>
        </form>
    </>
}

function ConfirmReasonDialog({onConfirm, id = "confirm-delete"}) {
    const [reason, setReason] = useState("")
    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">"Refuser la demande"</h4>
                </div>
                <div className="modal-body">
                    <div className="row mb-3">
                        <div className="col">
                            <label htmlFor="reason" className="form-label">Raison du refus</label>
                            <textarea className="form-control" id="reason" name="reason" rows="3"
                                      placeholder="Veuillez indiquer la raison du refus" value={reason}
                                      onChange={e => setReason(e.target.value)}></textarea>
                        </div>
                    </div>
                    <span>Êtes-vous sûr de vouloir refuser cette demande ?</span>
                </div>
                <div className="modal-footer">
                    <button type="button" className="btn btn-default" data-dismiss="modal" data-bs-dismiss="modal">Annuler</button>
                    <a className="btn btn-danger btn-ok" data-bs-dismiss="modal" onClick={_ => onConfirm(reason)}>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")

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


    return <div className="col mb-4">
        <div className="card">
            <div className="card-header">Membre n°{index + 1}</div>
            <input name={"mode" + index} value={mode} readOnly hidden/>
            <div className="card-body">
                <RoleList name={"role" + index} text="Rôle" 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}>Par n° de licence</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}>Par Membre similaire</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}>Par Nouveau membre</label>
                            </div>
                            <div className="card-body">
                                <TextField name={"lname" + index} text="Nom" value={member.lname} disabled={mode !== 2}/>
                                <TextField name={"fname" + index} text="Prénom" 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="nouvel email"
                               name={"flexRadioDefault" + index} checked={emailChoice === '0'}
                               onChange={e => setEmailChoice(e.target.value)}/>
                    </div>
                    <span className="input-group-text">Nouvel email</span>
                    <input type="Email" className="form-control" aria-label="nouvel email" defaultValue={member.email}
                           name={"new_email" + index}/>
                </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">Conserver l'ancien email</span>
                    <input type="Email" className="form-control" aria-label="ancien email" disabled={true}
                           name={"old_email" + index} value={email}/>
                </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)

    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}>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">Nom: {data.lname} {data.fname}, Club: {data.club ? data.club.name : "Sans club"}</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)

    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 : "Sans club"}</small>
            </button>
        })}
    </div>
}
