import {REJECT_PASSENGER_OFFICE} from "@/core/data/apiRoutes";
import {
    Button,
    Dialog,
    DialogActions,
    DialogContent,
    DialogTitle,
    IconButton,
    Stack,
    TextField,
    Tooltip,
    Typography,
} from "@mui/material";
import {useTranslations} from "next-intl";
import {useFormik} from "formik";
import * as Yup from "yup";
import {useState} from "react";
import UploadSystem from "@/core/components/UploadSystem";
import UploadFileNotification from "@/core/components/notifications/UploadFileNotification";
import useDirection from "@/lib/app/hooks/useDirection";
import ThumbDownIcon from "@mui/icons-material/ThumbDown";
import useRequest from "@/lib/app/hooks/useRequest";
import useNotification from "@/lib/app/hooks/useNotification";


const Reject = ({rowId, fetchUrl, mutate}) => {
    const [selectedImage, setSelectedImage] = useState("");
    const [fileType, setfileType] = useState(null);
    const [fileName, setfileName] = useState(null);
    const [showAddIcon, setShowAddIcon] = useState(true);
    const t = useTranslations();
    const {directionApp} = useDirection();
    const [openRejectDialog, setOpenRejectDialog] = useState(false);
    const requestServer = useRequest({auth: true})
    const {update_notification} = useNotification()

    const validationSchema = Yup.object().shape({
        description: Yup.string().required(t("RejectDialog.description_error")),
    });

    const formik = useFormik({
        initialValues: {
            description: "",
            reject_img: null
        },
        validationSchema,
        onSubmit: (values, {setSubmitting}) => {
            const formData = new FormData();
            formData.append("expert_description", values.description);
            if (values.reject_img != null) formData.append("attachment", values.reject_img);

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

    const handleDescriptionChange = (event) => {
        formik.setFieldValue("description", event.target.value);
        formik.handleChange(event);
    };
    const handleUploadChange = (event) => {
        const uploadedFile = event.target?.files?.[0];
        if (uploadedFile) {
            const maxFileSize = 2 * 1024 * 1024;
            if (uploadedFile.size > maxFileSize) {
                UploadFileNotification(t);
                event.target.value = "";
                return;
            }
            const fileType = event.target?.files?.[0].type;
            const fileName = event.target?.files?.[0].name;
            setSelectedImage(URL.createObjectURL(uploadedFile));
            setfileType(fileType);
            setfileName(fileName);
            formik.setFieldValue("reject_img", uploadedFile);
            setShowAddIcon(false);
        }
    };
    return (
        <>
            <Tooltip title={t("RejectDialog.reject")}>
                <IconButton color="primary" onClick={() => setOpenRejectDialog(true)}>
                    <ThumbDownIcon/>
                </IconButton>
            </Tooltip>
            <Dialog fullWidth open={openRejectDialog}
                    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("RejectDialog.reject")}</DialogTitle>
                <DialogContent>
                    <Stack spacing={2}>
                        <Stack>
                            <TextField
                                name="description"
                                multiline
                                rows={8}
                                label={t("RejectDialog.description")}
                                value={formik.values.description}
                                onChange={handleDescriptionChange}
                                onBlur={formik.handleBlur("description")}
                                error={
                                    formik.touched.description && Boolean(formik.errors.description)
                                }
                                helperText={formik.touched.description && formik.errors.description}
                                fullWidth
                                variant="outlined"
                                sx={{mt: 1}}
                            />
                        </Stack>
                        <Stack>
                            <Typography>{t("UploadSystem.upload_file")}{t("UploadSystem.optional")}</Typography>
                            <UploadSystem
                                selectedImage={selectedImage}
                                handleUploadChange={handleUploadChange} // Pass the updated function directly
                                setselectedImage={setSelectedImage}
                                setFieldValue={formik.setFieldValue} // Remove props.setFieldValue, use formik.setFieldValue
                                fieldname="reject_img"
                                fileType={fileType}
                                fileName={fileName}
                                imageAlt={t("app_name")}
                                imageSize={[250 /*width*/, 150 /*height*/]}
                                setShowAddIcon={setShowAddIcon}
                                showAddIcon={showAddIcon}
                            />
                        </Stack>
                    </Stack>
                </DialogContent>
                <DialogActions>
                    <Button onClick={() => setOpenRejectDialog(false)} variant="outlined" color="secondary"
                            disabled={formik.isSubmitting} autoFocus>
                        {t("RejectDialog.button-cancel")}
                    </Button>
                    <Button onClick={formik.handleSubmit} variant="contained" color="primary"
                            disabled={formik.isSubmitting || !formik.dirty || !formik.isValid}>
                        {t("RejectDialog.button-reject")}
                    </Button>
                </DialogActions>
            </Dialog>
        </>
    );
};
export default Reject;