import UploadSystem from "@/core/components/UploadSystem"
import useNotification from "@/lib/app/hooks/useNotification";
import useRequest from "@/lib/app/hooks/useRequest";
import {Button, DialogActions, DialogContent, FormHelperText, Grid, Stack, TextField, Typography} from "@mui/material"
import {useFormik} from "formik";
import {useTranslations} from "next-intl";
import {useState} from "react";
import * as Yup from "yup";
import {REJECT_PASSENGER_BOSS} from "@/core/data/apiRoutes";

const RejectContent = ({rowId, mutate, setOpenRejectDialog}) => {
    const [selectedImageAForm, setSelectedImageAForm] = useState("");
    const [selectedImageBForm, setSelectedImageBForm] = useState("");
    const [fileTypesA, setFileTypesA] = useState(null);
    const [fileNamesA, setFileNamesA] = useState(null);
    const [fileTypesB, setFileTypesB] = useState(null);
    const [fileNamesB, setFileNamesB] = useState(null);
    const [showAddIconA, setShowAddIconA] = useState(true);
    const [showAddIconB, setShowAddIconB] = useState(true);
    const t = useTranslations();
    const requestServer = useRequest({auth: true})
    const {update_notification} = useNotification()

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

        first_reject_img: Yup.mixed()
            .required(t("PassengerBoss.upload_file_first_required"))
            .test('fileSize', `${t("PassengerBoss.upload_file_unit")}`, (value) => {
                return value.size <= 2 * 1024 * 1024;
            })
            .test('fileType', `${t("PassengerBoss.upload_file_format")}`, (value) => {
                const allowedTypes = ['image/jpg', 'image/jpeg', 'image/png', 'application/pdf']; // Define your allowed file types
                return allowedTypes.includes(value.type);
            }),

        second_reject_img: Yup.mixed()
            .required(t("PassengerBoss.upload_file_second_required"))
            .test('fileSize', `${t("PassengerBoss.upload_file_unit")}`, (value) => {
                return value.size <= 2 * 1024 * 1024;
            })
            .test('fileType', `${t("PassengerBoss.upload_file_format")}`, (value) => {
                const allowedTypes = ['image/jpg', 'image/jpeg', 'image/png', 'application/pdf']; // Define your allowed file types
                return allowedTypes.includes(value.type);
            })
    });

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

            const attachments = [
                { title: 'فرم الف', file: values.first_reject_img },
                { title: 'فرم ب', file: values.second_reject_img }
            ];

            attachments.forEach((attachment, index) => {
                formData.append(`attachment[${index}][title]`, attachment.title);
                formData.append(`attachment[${index}][file]`, attachment.file);
            });

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

    const handleDescriptionChange = (event) => {
        formik.setFieldValue("description", event.target.value);
        formik.handleChange(event);
    };
    const handleUploadChangeAForm = (event) => {
        const uploadedFile = event.target?.files?.[0];
        if (uploadedFile) {
            const fileType = event.target?.files?.[0].type;
            const fileName = event.target?.files?.[0].name;
            setSelectedImageAForm(URL.createObjectURL(uploadedFile));
            setFileTypesA(fileType);
            setFileNamesA(fileName);
            formik.setFieldValue("first_reject_img", uploadedFile).then(() => {
                formik.setFieldTouched("first_reject_img", true);
            })
            setShowAddIconA(false);
        }
    };
    const handleUploadChangeBForm = (event) => {
        const uploadedFile = event.target?.files?.[0];
        if (uploadedFile) {
            const fileType = event.target?.files?.[0].type;
            const fileName = event.target?.files?.[0].name;
            setSelectedImageBForm(URL.createObjectURL(uploadedFile));
            setFileTypesB(fileType);
            setFileNamesB(fileName);
            formik.setFieldValue("second_reject_img", uploadedFile).then(() => {
                formik.setFieldTouched("second_reject_img", true);
            })
            setShowAddIconB(false);
        }
    };
    return (
        <>
            <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>
                        <Grid container spacing={2}>
                            <Grid item xs={12} sm={6}>
                                <Typography>{t("PassengerBoss.first_form")}</Typography>
                                <UploadSystem
                                    selectedImage={selectedImageAForm}
                                    handleUploadChange={handleUploadChangeAForm} // Pass the updated function directly
                                    setselectedImage={setSelectedImageAForm}
                                    setFieldValue={formik.setFieldValue} // Remove props.setFieldValue, use formik.setFieldValue
                                    fieldname="first_reject_img"
                                    fileType={fileTypesA}
                                    fileName={fileNamesA}
                                    imageAlt={t("app_name")}
                                    imageSize={[250, 150]}
                                    setShowAddIcon={setShowAddIconA}
                                    showAddIcon={showAddIconA}
                                    onBlur={() => formik.handleBlur("first_reject_img")}
                                    error={
                                        formik.touched.first_reject_img &&
                                        Boolean(formik.errors.first_reject_img)
                                    }
                                />
                                <FormHelperText
                                    error={Boolean(formik.errors.first_reject_img)}
                                >
                                    {formik.touched.first_reject_img && formik.errors.first_reject_img}
                                </FormHelperText>
                            </Grid>
                            <Grid item xs={12} sm={6}>
                                <Typography>{t("PassengerBoss.second_form")}</Typography>
                                <UploadSystem
                                    selectedImage={selectedImageBForm}
                                    handleUploadChange={handleUploadChangeBForm} // Pass the updated function directly
                                    setselectedImage={setSelectedImageBForm}
                                    setFieldValue={formik.setFieldValue} // Remove props.setFieldValue, use formik.setFieldValue
                                    fieldname="second_reject_img"
                                    fileType={fileTypesB} // Use fileTypes array at index 0 for the first instance
                                    fileName={fileNamesB}
                                    imageAlt={t("app_name")}
                                    imageSize={[250, 150]}
                                    setShowAddIcon={setShowAddIconB}
                                    showAddIcon={showAddIconB}
                                    onBlur={() => formik.handleBlur("second_reject_img")}
                                    error={
                                        formik.touched.second_reject_img &&
                                        Boolean(formik.errors.second_reject_img)
                                    }
                                />
                                <FormHelperText
                                    error={Boolean(formik.errors.second_reject_img)}
                                >
                                    {formik.touched.second_reject_img && formik.errors.second_reject_img}
                                </FormHelperText>
                            </Grid>
                        </Grid>
                    </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>
        </>
    )
}
export default RejectContent