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

const CreateContent = ({mutate, setOpenConfirmDialog}) => {
    const t = useTranslations();
    const requestServer = useRequest({auth: true})
    const {permissions_list, isLoading} = usePermissions()
    const validationSchema = Yup.object().shape({
        name: Yup.string().required(t("AddDialog.name_error")),
        name_fa: Yup.string().required(t("AddDialog.name_fa_error")),
        permissions: Yup.array().min(1, t("AddDialog.permission_min_error")).required(t("AddDialog.permission")),
    });
    const formik = useFormik({
        initialValues: {
            name: "",
            name_fa: "",
            permissions: [],
        }, 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(ADD_ROLE_MANAGEMENT, '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("AddDialog.name")}
                            type="text"
                            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("AddDialog.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("AddDialog.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("AddDialog.loading_permissions_list")}</Typography>
                                    </Stack>
                                    : (
                                        <Grid container spacing={2}>
                                            <>
                                                {permissions_list.map((permission, index) => (
                                                    <Grid key={permission.id} item xs={6} data-testid= "PermissionList-checkbox">
                                                        <FormControlLabel
                                                            control={
                                                                <Checkbox
                                                                    data-testid= {`PermissionList-checkbox-${index}`}
                                                                    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("AddDialog.button-cancel")}
                </Button>
                <Button onClick={formik.handleSubmit} variant="contained" color="primary"
                        disabled={formik.isSubmitting || !formik.dirty || !formik.isValid}>
                    {t("AddDialog.button-add")}
                </Button>
            </DialogActions>
        </>
    )
}
export default CreateContent