import {UPDATE_ROLE_MANAGEMENT} from "@/core/data/apiRoutes";
import useNotification from "@/lib/app/hooks/useNotification";
import usePermissions from "@/lib/app/hooks/usePermissions";
import useRequest from "@/lib/app/hooks/useRequest";
import {
    Button,
    Checkbox, CircularProgress,
    DialogActions,
    DialogContent,
    FormControl,
    FormControlLabel,
    FormHelperText,
    FormLabel,
    Grid,
    Stack,
    TextField, Typography
} from "@mui/material"
import {useFormik} from "formik";
import {useTranslations} from "next-intl";
import * as Yup from "yup";

const UpdateContent = ({row, mutate, setOpenConfirmDialog}) => {
    const t = useTranslations();
    const requestServer = useRequest({auth: true})
    const {update_notification} = useNotification()
    const {permissions_list, isLoading} = usePermissions()

    const validationSchema = Yup.object().shape({
        name: Yup.string().required(t("UpdateDialog.name_error")),
        name_fa: Yup.string().required(t("UpdateDialog.name_fa_error")),
        permissions: Yup.array().min(1, t("UpdateDialog.permission_min_error")).required(t("UpdateDialog.permission")),
    });

    const formik = useFormik({
        initialValues: {
            name: row.getValue("name"),
            name_fa: row.getValue("name_fa"),
            permissions: row.original.permissions.map((obj) => obj.id),
        }, validationSchema, onSubmit: (values, {setSubmitting}) => {
            const formData = new FormData();
            formData.append("name", values.name);
            formData.append("name_fa", values.name_fa);
            for (let i = 0; i < values.permissions.length; i++) {
                formData.append(`permissions[${i}]`, values.permissions[i]);
            }

            requestServer(`${UPDATE_ROLE_MANAGEMENT}/${row.getValue("id")}`, 'post', {
                data: formData,
            }).then((response) => {
                setOpenConfirmDialog(false)
                mutate()
                update_notification()
            }).catch(() => {
            }).finally(() => {
                setSubmitting(false);
            });
        },
    });
    return (
        <>
            <DialogContent>
                <Stack spacing={2}>
                    <Stack direction="row" spacing={2} sx={{mt: 1}}>
                        <TextField
                            name="name"
                            label={t("UpdateDialog.name")}
                            value={formik.values.name}
                            onChange={formik.handleChange}
                            fullWidth
                            variant="outlined"
                            onBlur={formik.handleBlur("name")}
                            error={formik.touched.name && Boolean(formik.errors.name)}
                            helperText={formik.touched.name && formik.errors.name}
                        />
                        <TextField
                            name="name_fa"
                            label={t("UpdateDialog.name_fa")}
                            value={formik.values.name_fa}
                            onChange={formik.handleChange}
                            fullWidth
                            variant="outlined"
                            onBlur={formik.handleBlur("name_fa")}
                            error={formik.touched.name_fa && Boolean(formik.errors.name_fa)}
                            helperText={formik.touched.name_fa && formik.errors.name_fa}
                        />
                    </Stack>
                    <Stack>
                        <FormLabel>{t("UpdateDialog.permission")}<br/>
                            <FormControl
                                name="permissions"
                                error={formik.touched.permissions && Boolean(formik.errors.permissions)}
                                onBlur={formik.handleBlur("permissions")}
                                sx={{mt: 2}}
                            >
                                <FormHelperText>{formik.touched.permissions && formik.errors.permissions}</FormHelperText>
                                {isLoading ?
                                    <Stack direction={'row'} alignItems={'center'} spacing={2}
                                           justifyContent={'center'}>
                                        <CircularProgress size={20}/>
                                        <Typography
                                            variant={'caption'}>{t("UpdateDialog.loading_permissions_list")}</Typography>
                                    </Stack>
                                    : (
                                        <Grid container spacing={2}>
                                            <>
                                                {permissions_list.map((permission) => (
                                                    <Grid key={permission.id} item xs={6}>
                                                        <FormControlLabel
                                                            control={
                                                                <Checkbox
                                                                    data-testid="PermissionList-checkbox"
                                                                    checked={formik.values.permissions.includes(permission.id)}
                                                                    onChange={(e) => {
                                                                        if (e.target.checked) {
                                                                            formik.setFieldValue("permissions", [...formik.values.permissions, permission.id])
                                                                        } else {
                                                                            formik.setFieldValue("permissions", formik.values.permissions.filter((id) => id !== permission.id))
                                                                        }
                                                                    }}
                                                                />
                                                            }
                                                            label={permission.name_fa}
                                                        />
                                                    </Grid>
                                                ))}
                                            </>
                                        </Grid>
                                    )
                                }
                            </FormControl>
                        </FormLabel>
                    </Stack>
                </Stack>
            </DialogContent>
            <DialogActions>
                <Button onClick={() => setOpenConfirmDialog(false)} variant="outlined" color="secondary"
                        disabled={formik.isSubmitting} autoFocus>
                    {t("UpdateDialog.button-cancel")}
                </Button>
                <Button onClick={formik.handleSubmit} variant="contained" color="primary"
                        disabled={formik.isSubmitting || !formik.dirty || !formik.isValid}>
                    {t("UpdateDialog.button-update")}
                </Button>
            </DialogActions>
        </>
    )
}
export default UpdateContent