import {useTranslations} from "next-intl";
import {useState} from "react";
import {
    Button,
    Dialog,
    DialogActions,
    DialogContent,
    DialogTitle,
    FormControl,
    FormHelperText,
    IconButton,
    InputLabel,
    MenuItem,
    Select,
    Stack,
    TextField,
    Tooltip
} from "@mui/material";
import {useFormik} from "formik";
import ChangeCircleIcon from '@mui/icons-material/ChangeCircle';
import {UPDATE_LOAN_MANAGEMENT_REFAHI} from "@/core/data/apiRoutes";
import useRequest from "@/lib/app/hooks/useRequest";
import useNotification from "@/lib/app/hooks/useNotification";
import * as Yup from "yup";
import useLoanStateRefahi from "@/lib/prefetchDataTable/hooks/useLoanStateRefahi";


const Update = ({rowId, fetchUrl, mutate}) => {
    const t = useTranslations();
    const {loan_state_refahi} = useLoanStateRefahi()
    const [openConfirmDialog, setOpenConfirmDialog] = useState(false);
    const requestServer = useRequest({auth: true})
    const {update_notification} = useNotification()

    const validationSchema = Yup.object().shape({
        description: Yup.string().required(t("UpdateDialog.description_error")),
        next_state_id: Yup.number().required(t("UpdateDialog.next-state-id-error"))
    });

    const formik = useFormik({
        initialValues: {
            description: "",
            next_state_id: ""
        },
        validationSchema,
        onSubmit: (values, {setSubmitting}) => {
            const formData = new FormData();
            formData.append("description", values.description);
            formData.append("next_state_id", values.next_state_id);

            requestServer(`${UPDATE_LOAN_MANAGEMENT_REFAHI}/${rowId}`, 'post', {
                data: formData,
            }).then((response) => {
                mutate(fetchUrl)
                update_notification()
            }).catch(() => {
            }).finally(() => {
                setSubmitting(false);
            });
        },
    });

    const handleDescriptionChange = (event) => {
        formik.setFieldValue("description", event.target.value)
    };
    const handleNextStateIDChange = (event) => {
        formik.setFieldValue("next_state_id", event.target.value)
    };

    return (
        <>
            <Tooltip title={t("UpdateDialog.update-tooltip")}>
                <IconButton
                    color="primary"
                    onClick={() => {
                        setOpenConfirmDialog(true)
                    }}
                >
                    <ChangeCircleIcon/>
                </IconButton>
            </Tooltip>
            <Dialog fullWidth open={openConfirmDialog}
                    PaperProps={{sx: {boxShadow: 'rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px'}}}>
                <DialogTitle>{t("UpdateDialog.update")}</DialogTitle>
                <DialogContent>
                    <Stack spacing={2}>
                        <Stack>
                            <TextField
                                name="description"
                                multiline
                                rows={8}
                                label={t("UpdateDialog.description")}
                                value={formik.values.description}
                                onChange={handleDescriptionChange}
                                fullWidth
                                variant="outlined"
                                sx={{mt: 1}}
                                onBlur={formik.handleBlur("description")}
                                error={
                                    formik.touched.description && Boolean(formik.errors.description)
                                }
                                helperText={formik.touched.description && formik.errors.description}
                            />
                        </Stack>
                        <Stack>
                            <FormControl
                                error={
                                    formik.touched.next_state_id &&
                                    Boolean(formik.errors.next_state_id)
                                } fullWidth>
                                <InputLabel>{t("UpdateDialog.next-state-id")}</InputLabel>
                                <Select
                                    labelId="next_state_id"
                                    id="next_state_id"
                                    value={formik.values.next_state_id}
                                    label={t("UpdateDialog.next-state-id")}
                                    onChange={handleNextStateIDChange}
                                    onBlur={formik.handleBlur("next_state_id")}
                                >
                                    {loan_state_refahi ? (loan_state_refahi.map((item) => {
                                        return (
                                            <MenuItem key={item.id} value={item.id}>{item.name}</MenuItem>
                                        )
                                    })) : null}
                                </Select>
                                <FormHelperText>
                                    {formik.touched.next_state_id && formik.errors.next_state_id}
                                </FormHelperText>
                            </FormControl>
                        </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}>
                        {t("UpdateDialog.button-update")}
                    </Button>
                </DialogActions>
            </Dialog>
        </>
    );
};
export default Update;