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 useDirection from "@/lib/app/hooks/useDirection";
import {useFormik} from "formik";
import UploadFileNotification from "@/core/components/notifications/UploadFileNotification";
import * as Yup from "yup";
import useRequest from "@/lib/app/hooks/useRequest";
import {CONFIRM_PASSENGER_BOSS} from "@/core/data/apiRoutes";
import useNotification from "@/lib/app/hooks/useNotification";
import PriceField from "@/core/components/PriceField";


const Confirm = ({rowId, fetchUrl, mutate}) => {
    const t = useTranslations();
    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 requestServer = useRequest({auth: true})
    const {update_notification} = useNotification()

    const validationSchema = Yup.object().shape({
        approved_amount: Yup.mixed().test(
            "is-number",
            `${t("ConfirmDialog.approved_amount_number")}`,
            (value) => !isNaN(value)
        ).test("positive", `${t("ConfirmDialog.approved_amount_positive")}`, (value) => value >= 0)
            .required(t("ConfirmDialog.approved_amount_error"))
    });
    const formik = useFormik({
        initialValues: {
            description: "",
            approved_amount: "",
            confirm_img: null
        },
        validationSchema,
        onSubmit: (values, {setSubmitting}) => {
            const formData = new FormData();
            formData.append("approved_amount", values.approved_amount);
            if (values.description != "") formData.append("expert_description", values.description);
            if (values.confirm_img != null) formData.append("attachment", values.confirm_img);

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

    const handleDescriptionChange = (event) => {
        formik.setFieldValue("description", event.target.value)
    };
    const handleAmountChange = (event) => {
        if (!isNaN(event.target.value)) {
            formik.setFieldValue("approved_amount", event.target.value)
        } else {
            formik.setFieldValue("approved_amount", formik.values.approved_amount)
        }
    };
    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("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>
                            <PriceField
                                name="approved_amount"
                                label={<>
                                    <span>{t("ConfirmDialog.approved_amount")}</span><small>{t("ConfirmDialog.unit")}</small></>}
                                type="text"
                                inputProps={{
                                    inputMode: "number",
                                    min: 0,
                                    pattern: "[0-9]*",
                                }}
                                onChange={handleAmountChange}
                                variant="outlined"
                                value={formik.values.approved_amount}
                                onBlur={formik.handleBlur("approved_amount")}
                                error={
                                    formik.touched.approved_amount &&
                                    Boolean(formik.errors.approved_amount)
                                }
                                helperText={
                                    formik.touched.approved_amount && formik.errors.approved_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;