import { Autocomplete, TextField } from "@mui/material";
import { useEditExerciseQuery, useEquipmentQuery } from "@/components/Exercises/queries";
import { useProfileQuery } from "@/components/User";
import React from "react";
import { useTranslation } from "react-i18next";

export function EditExerciseEquipment(props: { exerciseId: number, initial: number[] }) {
    const { t } = useTranslation();
    const [value, setValue] = React.useState<number[]>(props.initial);
    const equipmentQuery = useEquipmentQuery();
    const profileQuery = useProfileQuery();
    const editMutation = useEditExerciseQuery();

    const handleOnChange = async (newValue: number[]) => {
        setValue(newValue);

        await editMutation.mutateAsync({
            id: props.exerciseId,
            // eslint-disable-next-line camelcase
            data: { equipment: newValue, license_author: profileQuery.data!.username },
        });
    };

    return equipmentQuery.isSuccess
        ? <Autocomplete
            multiple
            value={value}
            options={equipmentQuery.data.map(e => e.id)}
            getOptionLabel={option => equipmentQuery.data.find(e => e.id === option)!.translatedName}
            onChange={(event, newValue) => handleOnChange(newValue)}
            renderInput={params => (
                <TextField
                    variant="standard"
                    label={t("exercises.equipment")}
                    value={value}
                    {...params}
                />
            )}
        />
        : null;
}