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

const Confirm = ({rowId, fetchUrl, mutate}) => {
    const t = useTranslations();
    const {token} = useUser();
    const {directionApp} = useDirection();
    const [selectedImage, setSelectedImage] = useState("");
    const [fileType, setfileType] = useState(null);
    const [fileName, setfileName] = useState(null);
    const [showAddIcon, setShowAddIcon] = useState(true);
    const [openConfirmDialog, setOpenConfirmDialog] = useState(false);

    const validationSchema = Yup.object().shape({
        proposed_amount: Yup.number().positive(t("ConfirmDialog.proposed_amount_positive")).required(t("ConfirmDialog.proposed_amount_error")),
    })
    const formik = useFormik({
        initialValues: {
            description: "",
            proposed_amount: "",
            confirm_img: ""
        },
        validationSchema,
        onSubmit: (values) => {
            const formData = new FormData();
            formData.append("proposed_amount", values.proposed_amount);
            if (values.description != "") formData.append("expert_description", values.description);
            Notifications(directionApp, t, undefined)
            axios
                .post(`${CONFIRM_MACHINARY_OFFICE}/${rowId}`, formData, {
                    headers: {authorization: `Bearer ${token}`},
                })
                .then((response) => {
                    Notifications(directionApp, t, response);
                    mutate(fetchUrl)
                    formik.setSubmitting(false)
                })
                .catch((error) => {
                    Notifications(directionApp, t, error.response);
                    formik.setSubmitting(false)
                });
        },
    });

    const handleDescriptionChange = (event) => {
        formik.setFieldValue("description", event.target.value)
    };
    const handleAmountChange = (event) => {
        formik.setFieldValue("proposed_amount", event.target.value);
    };
    const handleUploadChange = (event) => {
        const uploadedFile = event.target?.files?.[0];
        if (uploadedFile) {
            const maxFileSize = 2 * 1024 * 1024;
            if (uploadedFile.size > maxFileSize) {
                UploadFileNotification(directionApp, 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("confirm_img", uploadedFile);
            setShowAddIcon(false);
        }
    };
    return (
        <>
            <Tooltip title={t("ConfirmDialog.confirm")}>
                <IconButton
                    color="primary"
                    onClick={() => {
                        setOpenConfirmDialog(true)
                    }}
                >
                    <ThumbUpAltIcon/>
                </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("ConfirmDialog.confirm")}</DialogTitle>
                <DialogContent>
                    <Stack spacing={2}>
                        <Stack>
                            <TextField
                                name="description"
                                multiline
                                rows={8}
                                label={<>
                                    <span>{t("ConfirmDialog.description")}</span><small>{t("ConfirmDialog.optional")}</small></>}
                                value={formik.values.description}
                                onChange={handleDescriptionChange}
                                fullWidth
                                variant="outlined"
                                sx={{mt: 1}}
                            />
                        </Stack>
                        <Stack>
                            <TextField
                                name="proposed_amount"
                                label={<>
                                    <span>{t("ConfirmDialog.proposed_amount")}</span><small>{t("ConfirmDialog.unit")}</small></>}
                                type="number"
                                inputProps={{
                                    min: 0,
                                    pattern: "[0-9]*",
                                }}
                                variant="outlined"
                                value={formik.values.proposed_amount}
                                onChange={handleAmountChange}
                                onBlur={formik.handleBlur("proposed_amount")}
                                error={
                                    formik.touched.proposed_amount &&
                                    Boolean(formik.errors.proposed_amount)
                                }
                                helperText={
                                    formik.touched.proposed_amount && formik.errors.proposed_amount
                                }
                                sx={{mt: 1}}
                                fullWidth
                            />
                        </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="confirm_img"
                                fileType={fileType}
                                fileName={fileName}
                                imageAlt={t("app_name")}
                                imageSize={[250, 150]}
                                setShowAddIcon={setShowAddIcon}
                                showAddIcon={showAddIcon}
                            />
                        </Stack>
                    </Stack>
                </DialogContent>
                <DialogActions>
                    <Button onClick={() => setOpenConfirmDialog(false)} variant="outlined" color="secondary"
                            disabled={formik.isSubmitting} autoFocus>
                        {t("ConfirmDialog.button-cancel")}
                    </Button>
                    <Button onClick={formik.handleSubmit} variant="contained" color="primary"
                            disabled={formik.isSubmitting}>
                        {t("ConfirmDialog.button-confirm")}
                    </Button>
                </DialogActions>
            </Dialog>
        </>
    );
};
export default Confirm;