import {FormControl, FormHelperText, Grid, InputLabel, MenuItem, Select} from "@mui/material";
import {useTranslations} from "next-intl";
import useProvince from "@/lib/app/hooks/useProvince";
import useRequest from "@/lib/app/hooks/useRequest";

const Province = ({formik}) => {
    const t = useTranslations();
    const requestServer = useRequest()
    const {provinceList, isLoadingProvinceList, errorProvinceList} = useProvince();

    return (
        <Grid container justifyContent="space-around" spacing={2} sx={{pb: 2}}>
            <Grid item xs={12} sm={6}>
                <FormControl
                    error={formik.touched.province_id && !!formik.errors.province_id}
                    sx={{width: "100%", mt: 2}}
                    size="small"
                >
                    <InputLabel>{t("ExpertMangement.text_field_province_id")}</InputLabel>
                    <Select
                        name="province_id"
                        disabled={isLoadingProvinceList || errorProvinceList}
                        label={t("ExpertMangement.text_field_province_id")}
                        value={isLoadingProvinceList || errorProvinceList ? "" : formik.values.province_id}
                        onChange={(e) => {
                            formik.setFieldValue("province_id", e.target.value);
                        }}
                        inputProps={{
                            "data-testid": "input-province-id"
                        }}
                        data-testid="select-box"
                        SelectDisplayProps={{"data-testid": 'option-opener-province'}}
                        onBlur={formik.handleBlur}
                        fullWidth
                        variant="outlined"
                    >
                        {isLoadingProvinceList ? (
                            <MenuItem>
                                {t("ExpertMangement.text_field_loading_provinces_list")}
                            </MenuItem>
                        ) : errorProvinceList ? (
                            <MenuItem>
                                {t("ExpertMangement.text_field_error_fetching_provinces")}
                            </MenuItem>
                        ) : (
                            provinceList.map((item) => (
                                <MenuItem key={item.id} value={item.id}>
                                    {item.name}
                                </MenuItem>
                            ))
                        )}
                    </Select>
                    <FormHelperText>
                        {formik.touched.province_id && formik.errors.province_id ? formik.errors.province_id : ""}
                    </FormHelperText>
                </FormControl>
            </Grid>
        </Grid>
    )
}
export default Province