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

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

    const validationSchema = Yup.object().shape({
        name_en: Yup.string().required(t("UpdateDialog.name_en_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_en: 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_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(`${UPDATE_ROLE}/${row.getValue("id")}`, 'post', {
                data: formData,
            }).then((response) => {
                setOpenConfirmDialog(false)
                mutate()
                update_notification()
            }).catch(() => {
            }).finally(() => {
                setSubmitting(false);
            });
        },
    });

    return (
        <>
            <DialogTitle>{t("UpdateDialog.update")}</DialogTitle>
            <DialogContent>
                <Stack sx={{mt: 2}} spacing={2}>
                    <Stack direction="row" spacing={2} sx={{mt: 1}}>
                        <TextField
                            name="name_en"
                            label={t("UpdateDialog.name_en")}
                            value={formik.values.name_en}
                            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("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}}
                                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("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