import {useNavigate, useParams} from "react-router-dom";
import {LoadingProvider, useLoadingSwitcher} from "../../../hooks/useLoading.jsx";
import {useFetch} from "../../../hooks/useFetch.js";
import {toast} from "react-toastify";
import {apiAxios, getToastMessage} from "../../../utils/Tools.js";
import {ConfirmDialog} from "../../../components/ConfirmDialog.jsx";
import {AxiosError} from "../../../components/AxiosError.jsx";
import {AffiliationCard} from "./AffiliationCard.jsx";
import {CountryList, TextField} from "../../../components/MemberCustomFiels.jsx";

import {useRef, useState} from "react";
import {LocationEditor, LocationEditorModal} from "../../../components/Club/LocationEditor.jsx";
import {ContactEditor} from "../../../components/Club/ContactEditor.jsx";
import {HoraireEditor} from "../../../components/Club/HoraireEditor.jsx";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faFilePdf} from "@fortawesome/free-solid-svg-icons";
import {SmartLogoBackground} from "../../../components/SmartLogoBackground.jsx";
import {useTranslation} from "react-i18next";

const vite_url = import.meta.env.VITE_URL;

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

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

    const handleRm = () => {
        toast.promise(
            apiAxios.delete(`/club/${id}`), getToastMessage("club.toast.del")
        ).then(_ => {
            navigate("/admin/club")
        })
    }

    return <>
        <h2>{t('pageClub')}</h2>
        <button type="button" className="btn btn-link" onClick={() => navigate("/admin/club")}>
            {t('back')}
        </button>
        {data
            ? <div>
                <div className="row">
                    <div className="col-lg-9">
                        <LoadingProvider>
                            <InformationForm data={data}/>
                        </LoadingProvider>
                    </div>
                    <div className="col-lg-3">
                        <LoadingProvider><AffiliationCard clubData={data}/></LoadingProvider>
                        <LoadingProvider><BureauCard clubData={data}/></LoadingProvider>
                        <div className="col" style={{textAlign: 'right', marginTop: '1em'}}>
                            <button className="btn btn-danger btn-sm" data-bs-toggle="modal"
                                    data-bs-target="#confirm-delete">{t('supprimerLeClub')}
                            </button>
                        </div>
                        <ConfirmDialog title={t('supprimerLeClub')}
                                       message={t('supprimerLeClub.msg')}
                                       onConfirm={handleRm}/>

                    </div>
                </div>
            </div>
            : error && <AxiosError error={error}/>
        }
    </>
}

function InformationForm({data}) {
    const [switchOn, setSwitchOn] = useState(data.international);
    const [modal, setModal] = useState({id: -1})
    const locationModalCallback = useRef(null)
    const {t} = useTranslation();

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

        const formData = new FormData(event.target);

        toast.promise(apiAxios.put(`/club/${data.id}`, formData), getToastMessage("club.toast.save"))
    }

    return <>
        <form onSubmit={handleSubmit} autoComplete="off">
            <div className="card mb-4">
                <input name="id" value={data.id} readOnly hidden/>
                <input name="clubId" value={data.clubId} readOnly hidden/>
                <div className="card-header">{t('affiliationNo', {no: data.no_affiliation})}</div>
                <div className="card-body text-center">

                    <TextField name="name" text={t('nom')} value={data.name}/>
                    <CountryList name="country" text={t('pays')} value={data.country}/>

                    <SmartLogoBackground
                        src={`${vite_url}/api/club/${data.clubId}/logo`}
                        alt="avatar"
                        imgClassName="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="input-group mb-3">
                        <div className="input-group-text">
                            <input type="checkbox" className="form-check-input mt-0" name="international" id="international"
                                   checked={switchOn} onChange={() => setSwitchOn(!switchOn)}/>
                            <label className="input-group-text" htmlFor="international">{t('clubExterne')}</label>
                        </div>
                    </div>
                    {!switchOn && <>
                        <TextField name="state_id" text={t('siretOuRna')} value={data.state_id} required={false}/>
                        <TextField name="contact_intern" text={t('contactInterne')} value={data.contact_intern} required={false}
                                   placeholder="example@test.com"/>
                        <TextField name="address" text={t('adresseAdministrative')} value={data.address} required={false}
                                   placeholder={t('adresseAdministrative')}/>

                        <div className="mb-3">
                            <div className="input-group">
                                <label className="input-group-text" htmlFor="status">{t('statue')}</label>
                                <a href={`${vite_url}/api/club/${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>

                        <ContactEditor data={data}/>
                        <LocationEditor data={data} setModal={setModal} sendData={locationModalCallback}/>
                        <HoraireEditor data={data}/>
                    </>
                    }
                </div>
                <div className="row mb-3">
                    <div className="d-grid gap-2 d-md-flex justify-content-md-end">
                        <button type="submit" className="btn btn-primary">{t('button.enregistrer')}</button>
                    </div>
                </div>
            </div>
        </form>

        <LocationEditorModal modal={modal} sendData={locationModalCallback}/>
    </>
}


export function BureauCard({clubData}) {
    const setLoading = useLoadingSwitcher()
    const {data, error} = useFetch(`/club/desk/${clubData.id}`, setLoading, 1)
    const navigate = useNavigate();
    const {t} = useTranslation();

    return <>
        <div className="card mb-4">
            <div className="card-header">{t('bureau')}</div>
            <div className="card-body">
                <ul className="list-group">
                    {data && data.map((d, index) => {
                        return <div key={index} className="list-group-item d-flex justify-content-between align-items-start list-group-item-action"
                                    onClick={__ => navigate(`/admin/member/${d.id}`)}>
                            <div className="me-auto"><small>{d.role}</small><br/>{d.lname} {d.fname}</div>
                        </div>
                    })}
                </ul>
            </div>
        </div>
        {error && <AxiosError error={error}/>}
    </>
}
