import {useTranslations} from "next-intl";
import {
    Box,
    Button,
    Chip,
    DialogActions,
    DialogContent,
    Divider,
    FormControl,
    FormHelperText,
    Grid,
    InputLabel,
    MenuItem,
    Select,
    TextField
} from "@mui/material";
import {useEffect, useState} from "react";
import {useFormik} from "formik";
import {GET_CITY_LIST, GET_PROVINCE_LIST, GET_ROLE_LIST, UPDATE_EXPERT_MANAGEMENT} from "@/core/data/apiRoutes";
import * as Yup from "yup";
import useRequest from "@/lib/app/hooks/useRequest";
import useProvince from "@/lib/app/hooks/useProvince";


const UpdateContent = ({row, fetchUrl, mutate, setOpenUpdateDialog}) => {
    const t = useTranslations();
    const requestServer = useRequest();
    // const [provinceList, setProvinceList] = useState([]);
    const [cityList, setCityList] = useState([]);
    const [roleList, setRoleList] = useState([]);
    const [cityTextField, setCityTextField] = useState(t("ExpertMangement.text_field_please_select_province"));
    const {provinceList, isLoadingProvinceList, errorProvinceList} = useProvince();

    useEffect(() => {
        requestServer(GET_ROLE_LIST, "get", {auth: true, notification: false})
            .then(({data}) => {
                const result = data.data;
                const formattedData = result.map((role, index) => ({
                    id: index,
                    name: role.name,
                    name_fa: role.name_fa,
                    value: role.id,
                }));
                setRoleList(formattedData);
            }).catch(() => {
        });
    }, []);

    function getCities(province_id) {
        formik.setFieldTouched("city_id", false, false);
        // formik.setFieldValue("city_id", "")
        setCityTextField(t("ExpertMangement.text_field_loading_cities_list"))
        requestServer(`${GET_CITY_LIST}?province_id=${province_id}`, "get", {auth: true, notification: false})
            .then(({data}) => {
                const result = data.data;
                const formattedData = result.map((city, index) => ({
                    id: index,
                    name: city.name,
                    value: city.id,
                }));
                setCityList(formattedData);
                setCityTextField(t("ExpertMangement.text_field_city_id"))
            }).catch(() => {
            setCityTextField(t("ExpertMangement.text_field_error_fetching_cities"))
        });
    }


    const validationSchema = Yup.object().shape({
        name: Yup.string().required(t("ExpertMangement.error_message_name")),
        username: Yup.string().required(t("ExpertMangement.error_message_username")),
        email: Yup.string().required(t("ExpertMangement.error_message_email")),
        phone_number: Yup.string().required(t("ExpertMangement.error_message_phone_number")),
        national_id: Yup.string().required(t("ExpertMangement.error_message_national_id")),
        password: Yup.string().required(t("ExpertMangement.error_message_password")),
        position: Yup.string().required(t("ExpertMangement.error_message_position")),
        province_id: Yup.string().required(t("ExpertMangement.error_message_province_id")),
        city_id: Yup.string().required(t("ExpertMangement.error_message_city_id")),
        role_id: Yup.string().required(t("ExpertMangement.error_message_role_id"))
    });
    const formik = useFormik({
        initialValues: {
            name: row.original.name,
            username: row.original.username,
            email: row.original.email,
            phone_number: row.original.phone_number,
            national_id: row.original.national_id,
            position: row.original.position,
            province_id: row.original.province_id,
            city_id: row.original.city_id,
            role_id: row.original.role_id
        },
        validationSchema,
        onSubmit: (values, {setSubmitting}) => {
            const formData = new FormData();
            formData.append("name", values.name);
            formData.append("national_id", values.national_id);
            formData.append("phone_number", values.phone_number);
            formData.append("email", values.email);
            formData.append("username", values.username);
            formData.append("province_id", values.province_id);
            formData.append("city_id", values.city_id);
            formData.append("position", values.position);
            formData.append("role_id", values.role_id);

            requestServer(`${UPDATE_EXPERT_MANAGEMENT}/${row.original.id}`, 'post', {auth: true, data: formData})
                .then((response) => {
                    mutate(fetchUrl)
                }).catch(() => {
            }).finally(() => {
                setSubmitting(false);
            });
        },
    });

    return (
        <>
            <DialogContent>
                <Box sx={{my: 1}}>
                    <Divider>
                        <Chip
                            label={t("ExpertMangement.personal_info")}
                        />
                    </Divider>
                </Box>
                <Grid container justifyContent="space-around" spacing={2} sx={{pb: 2}}>
                    <Grid item xs={12} sm={6} md={4} lg={3}>
                        <TextField
                            name="name"
                            label={t("ExpertMangement.text_field_name")}
                            variant="outlined"
                            margin="normal"
                            size="small"
                            value={formik.values.name}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                            error={formik.touched.name && !!formik.errors.name}
                            helperText={formik.touched.name && formik.errors.name ? formik.errors.name : null}
                            sx={{width: "100%"}}
                        />
                    </Grid>
                    <Grid item xs={12} sm={6} md={4} lg={3}>
                        <TextField
                            name="national_id"
                            label={t("ExpertMangement.text_field_national_id")}
                            variant="outlined"
                            margin="normal"
                            size="small"
                            value={formik.values.national_id}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                            error={formik.touched.national_id && !!formik.errors.national_id}
                            helperText={formik.touched.national_id && formik.errors.national_id ? formik.errors.national_id : null}
                            sx={{width: "100%"}}
                        />
                    </Grid>
                    <Grid item xs={12} sm={6} md={4} lg={3}>
                        <TextField
                            name="phone_number"
                            label={t("ExpertMangement.text_field_phone_number")}
                            variant="outlined"
                            margin="normal"
                            size="small"
                            value={formik.values.phone_number}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                            error={formik.touched.phone_number && !!formik.errors.phone_number}
                            helperText={formik.touched.phone_number && formik.errors.phone_number ? formik.errors.phone_number : null}
                            sx={{width: "100%"}}
                        />
                    </Grid>
                    <Grid item xs={12} sm={6} md={4} lg={3}>
                        <TextField
                            name="email"
                            label={t("ExpertMangement.text_field_email")}
                            variant="outlined"
                            margin="normal"
                            size="small"
                            value={formik.values.email}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                            error={formik.touched.email && !!formik.errors.email}
                            helperText={formik.touched.email && formik.errors.email ? formik.errors.email : null}
                            sx={{width: "100%"}}
                        />
                    </Grid>
                </Grid>
                <Box sx={{my: 1}}>
                    <Divider>
                        <Chip
                            label={t("ExpertMangement.user_info")}
                        />
                    </Divider>
                </Box>
                <Grid container justifyContent="space-around" spacing={2} sx={{pb: 2}}>
                    <Grid item xs={12} sm={6}>
                        <TextField
                            name="username"
                            label={t("ExpertMangement.text_field_username")}
                            variant="outlined"
                            margin="normal"
                            size="small"
                            value={formik.values.username}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                            error={formik.touched.username && !!formik.errors.username}
                            helperText={formik.touched.username && formik.errors.username ? formik.errors.username : null}
                            sx={{width: "100%"}}
                        />
                    </Grid>
                </Grid>
                <Box sx={{my: 1}}>
                    <Divider>
                        <Chip
                            label={t("ExpertMangement.rest_info")}
                        />
                    </Divider>
                </Box>
                <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"
                                label={t("ExpertMangement.text_field_province_id")}
                                value={formik.values.province_id}
                                onChange={(e) => {
                                    formik.setFieldValue("province_id", e.target.value);
                                    getCities(e.target.value)
                                }}
                                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 item xs={12} sm={6}>
                        <FormControl
                            disabled={cityList.length === 0}
                            error={formik.touched.city_id && !!formik.errors.city_id}
                            sx={{width: "100%", mt: 2}}
                            size="small"
                        >
                            <InputLabel>{cityTextField}</InputLabel>
                            <Select
                                name="city_id"
                                label={t("ExpertMangement.text_field_city_id")}
                                value={formik.values.city_id}
                                onChange={formik.handleChange}
                                onBlur={formik.handleBlur}
                                fullWidth
                                variant="outlined"
                            >
                                {cityList.map((item) => (
                                    <MenuItem key={item.value} value={item.value}>
                                        {item.name}
                                    </MenuItem>
                                ))}
                            </Select>
                            <FormHelperText>
                                {formik.touched.city_id && formik.errors.city_id ? formik.errors.city_id : ""}
                            </FormHelperText>
                        </FormControl>
                    </Grid>
                </Grid>
                <Grid container justifyContent="space-around" spacing={2} sx={{pb: 2}}>
                    <Grid item xs={12} sm={6}>
                        <TextField
                            name="position"
                            label={t("ExpertMangement.text_field_position")}
                            variant="outlined"
                            margin="normal"
                            size="small"
                            value={formik.values.position}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                            error={formik.touched.position && !!formik.errors.position}
                            helperText={formik.touched.position && formik.errors.position ? formik.errors.position : null}
                            sx={{width: "100%"}}
                        />
                    </Grid>
                    <Grid item xs={12} sm={6}>
                        <FormControl
                            error={formik.touched.role_id && !!formik.errors.role_id}
                            sx={{width: "100%", mt: 2}}
                            size="small"
                        >
                            <InputLabel>{t("ExpertMangement.text_field_role_id")}</InputLabel>
                            <Select
                                name="role_id"
                                label={t("ExpertMangement.text_field_role_id")}
                                value={formik.values.role_id}
                                onChange={formik.handleChange}
                                onBlur={formik.handleBlur}
                                fullWidth
                                variant="outlined"
                            >
                                {roleList.map((item) => (
                                    <MenuItem key={item.value} value={item.value}>
                                        {item.name_fa}
                                    </MenuItem>
                                ))}
                            </Select>
                            <FormHelperText>
                                {formik.touched.role_id && formik.errors.role_id ? formik.errors.role_id : ""}
                            </FormHelperText>
                        </FormControl>
                    </Grid>
                </Grid>
            </DialogContent>
            <DialogActions>
                <Button onClick={() => setOpenUpdateDialog(false)} variant="outlined" color="secondary"
                        disabled={formik.isSubmitting} autoFocus>
                    {t("ExpertMangement.button-cancel")}
                </Button>
                <Button onClick={formik.handleSubmit} variant="contained" color="primary"
                        disabled={formik.isSubmitting}>
                    {t("ExpertMangement.button-confirm")}
                </Button>
            </DialogActions>
        </>
    );
};
export default UpdateContent;