import {
    Button,
    Checkbox,
    CircularProgress,
    DialogActions,
    DialogContent,
    DialogTitle,
    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} 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_en: Yup.string().required(t("AddDialog.name_en_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_en: "",
            name_fa: "",
            permissions: [],
        }, validationSchema, onSubmit: (values, {setSubmitting}) => {
            const formData = new FormData();
            formData.append("name", values.name_en);
            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, 'post', {
                data: formData,
            }).then(() => {
                setOpenConfirmDialog(false)
                mutate()
                update_notification()
            }).catch(() => {
            }).finally(() => {
                setSubmitting(false);
            });
        },
    });

    return (
        <>
            <DialogTitle>{t("AddDialog.add")}</DialogTitle>
            <DialogContent>
                <Stack sx={{mt: 2}} spacing={2}>
                    <Stack direction="row" spacing={2}>
                        <TextField
                            name="name_en"
                            label={t("AddDialog.name_en")}
                            type="text"
                            value={formik.values.name}
                            onChange={formik.handleChange}
                            fullWidth
                            variant="outlined"
                            onBlur={formik.handleBlur("name_en")}
                            error={formik.touched.name_en && Boolean(formik.errors.name_en)}
                            helperText={formik.touched.name_en && formik.errors.name_en}

                        />
                        <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}}
                                fullWidth
                            >
                                <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) => (
                                                    <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("AddDialog.button-cancel")}
                </Button>
                <Button onClick={formik.handleSubmit} variant="contained" color="primary"
                        disabled={formik.isSubmitting}>
                    {t("AddDialog.button-add")}
                </Button>
            </DialogActions>
        </>
    )
}
export default CreateContent