import {useLoadingSwitcher} from "../../../hooks/useLoading.jsx";
import {apiAxios, errFormater, getToastMessage} from "../../../utils/Tools.js";
import {toast} from "react-toastify";
import imageCompression from "browser-image-compression";
import {BirthDayField, CountryList, OptionField, RoleList, TextField} from "../../../components/MemberCustomFiels.jsx";
import {ClubSelect} from "../../../components/ClubSelect.jsx";
import {useTranslation} from "react-i18next";

export function addPhoto(event, formData, send) {
    const imageFile = event.target.url_photo.files[0];
    if (imageFile) {
        console.log(`originalFile size ${imageFile.size / 1024 / 1024} MB`);

        const options = {
            maxSizeMB: 1,
            maxWidthOrHeight: 1920,
            useWebWorker: true,
        }

        imageCompression(imageFile, options).then(compressedFile => {
            console.log(`compressedFile size ${compressedFile.size / 1024 / 1024} MB`); // smaller than maxSizeMB
            formData.append("photo_data", compressedFile)
            send(formData)
        });
    } else {
        send(formData)
    }
}

export function InformationForm({data}) {
    const setLoading = useLoadingSwitcher()
    const {t} = useTranslation();

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

        let error = false;
        if (event.target.country?.value === "NA") {
            toast.error(t('membre.info.error1'));
            error = true;
        }
        if (event.target.club?.value === t('selectionner...')) {
            toast.error(t('membre.info.error2'));
            error = true;
        }

        if (error) {
            setLoading(0)
            return;
        }

        const formData = new FormData();
        formData.append("id", data.id);
        formData.append("lname", event.target.lname?.value.toUpperCase());
        formData.append("fname", event.target.fname?.value);
        formData.append("categorie", (event.target.category?.value.length === 0) ? null : event.target.category?.value);
        formData.append("club", event.target.club?.value);
        formData.append("genre", event.target.genre?.value);
        formData.append("country", event.target.country?.value);
        formData.append("birth_date", (event.target.birth_date?.value.length === 0) ? null : new Date(event.target.birth_date?.value).toUTCString());
        formData.append("email", event.target.email?.value);
        formData.append("role", event.target.role?.value);
        formData.append("grade_arbitrage", event.target.grade_arbitrage?.value);

        const send = (formData_) => {
            toast.promise(
                apiAxios.put(`/member/${data.id}`, formData_, {
                    headers: {
                        'Accept': '*/*',
                        'Content-Type': 'multipart/form-data',
                    }
                }), getToastMessage("membre.toast.save")
            ).finally(() => {
                if (setLoading)
                    setLoading(0)
            })
        }
        addPhoto(event, formData, send);
    }

    return <form onSubmit={handleSubmit} autoComplete="off">
        <div className="card mb-4">
            <div className="card-header">{t('information')}</div>
            <div className="card-body">
                <TextField name="lname" text={t('nom')} value={data.lname}/>
                <TextField name="fname" text={t('prenom')} value={data.fname}/>
                <TextField name="email" text={t('email')} value={data.email} placeholder="name@example.com"
                           type="email" required={false}/>
                <OptionField name="genre" text={t('genre')} value={data.genre}
                             values={{NA: 'N/A', H: 'H', F: 'F'}}/>
                <CountryList name="country" text={t('pays')} value={data.country}/>
                <BirthDayField inti_date={data.birth_date ? data.birth_date.split('T')[0] : ''}
                               inti_category={data.categorie} required={false}/>
                <div className="row">
                    <ClubSelect defaultValue={data?.club?.id} name="club" na={true}/>
                </div>
                <RoleList name="role" text={t('role')} value={data.role}/>
                <OptionField name="grade_arbitrage" text={t('gradeDarbitrage')} value={data.grade_arbitrage}
                             values={{NA: 'N/A', ASSESSEUR: 'Assesseur', ARBITRE: 'Arbitre'}}/>
                <div className="row">
                    <div className="input-group mb-3">
                        <label className="input-group-text" htmlFor="url_photo">{t('photos')} {t('(optionnelle)')}</label>
                        <input type="file" className="form-control" id="url_photo" name="url_photo"
                               accept=".jpg,.jpeg,.gif,.png,.svg"/>
                    </div>
                </div>
                <div className="row">
                    <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>
        </div>
    </form>;
}
