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,
    LinearProgress,
    Stack,
    TextField,
    Typography
} from "@mui/material"
import {useFormik} from "formik";
import {useTranslations} from "next-intl";
import {CONFIRM_PASSENGER_BOSS, EXPORT_PASSENGER_BOSS_DETAILS,} from "@/core/data/apiRoutes";
import {useEffect, useState} from "react";
import PriceField from "@/core/components/PriceField";
import * as Yup from "yup";
import CustomAccordion from "@/core/components/CustomAccordion";
import ImageContent from "@/core/components/ImageContent";
import NumberShowBox from "@/core/components/NumberShowBox";

const vehicle_amount = {
    "اتوبوس": 7000,
    "مینی بوس": 2000,
}
const ConfirmContent = ({rowId, mutate, setOpenConfirmDialog, vehicle_type, handleSizeChangeClick}) => {
    const t = useTranslations();
    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 requestServer = useRequest({auth: true, notification: false})
    const {update_notification} = useNotification();
    const [attachmentsData, setAttachmentsData] = useState([]);
    const [accordionStates, setAccordionStates] = useState([]);
    const [hasImageShown, setHasImageShown] = useState(false);
    const [imageLink, setImageLink] = useState(null);
    const [detailsList, setDetailsData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [isSkeleton, setIsSkeleton] = useState(false);

    useEffect(() => {
        requestServer(`${EXPORT_PASSENGER_BOSS_DETAILS}/${rowId}`, 'get')
            .then((response) => {
                const allAttachments = [];
                response.data.data.histories.map((history) => {
                    history.attachments.map((attachment) => {
                        allAttachments.push(attachment);
                    });
                });
                setDetailsData(response.data);
                setAttachmentsData(allAttachments);
                setDetailsData(response.data)
            })
            .catch(() => {
            }).finally(() => {
            setLoading(false);
        });
    }, []);

    useEffect(() => {
        if (attachmentsData.length !== 0) {
            const booleanData = Array.from({length: attachmentsData.length}, () => false);
            setAccordionStates(booleanData);
        }
    }, [attachmentsData]);

    const handleAccordionChange = (index) => {
        const newAccordionStates = accordionStates.map((state, i) => i === index ? !state : false);
        setAccordionStates(newAccordionStates);

        if (!newAccordionStates[index]) {
            handleSizeChangeClick('sm');
            setHasImageShown(false);
            setIsSkeleton(false)
        } else {
            handleSizeChangeClick('xl');
            setHasImageShown(true);
            setImageLink(attachmentsData[index])
            setIsSkeleton(true)
        }
    };


    const validationSchema = Yup.object().shape({
        approved_amount: Yup.mixed().test(
            "is-number",
            `${t("ConfirmDialog.approved_amount_number")}`,
            (value) => !isNaN(value)
        ).test("max-amount", `${t("PassengerBoss.max_amount", {value: parseInt(vehicle_amount[vehicle_type]).toLocaleString('en')})}`,
            (value) => value <= vehicle_amount[vehicle_type])
            .test("positive", `${t("ConfirmDialog.approved_amount_positive")}`, (value) => value >= 0)
            .required(t("ConfirmDialog.approved_amount_error")),
        first_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_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: "",
            approved_amount: "",
            first_img: null,
            second_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);

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

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

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

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

    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_img", uploadedFile).then(() => {
                formik.setFieldTouched("first_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_img", uploadedFile).then(() => {
                formik.setFieldTouched("second_img", true);
            })
            setShowAddIconB(false);
        }
    };
    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 renderCustomAccordions = () => {
        if (attachmentsData) {
            return attachmentsData.map((file, index) => (
                <CustomAccordion
                    key={index}
                    title={`${file.title}`}
                    hasOpened={accordionStates[index]}
                    hasAccordionOpened={null}
                    handleAccordionChange={() => handleAccordionChange(index)}
                    accordionIndex={index}
                    downloadFile={file.file}
                />
            ));
        }
        return null;
    };
    return (
        <>
            <DialogContent>
                <Grid container spacing={2}>
                    <Grid item xs={hasImageShown ? 6 : 12}>
                        {loading ? <LinearProgress/> :
                            <>
                                <NumberShowBox
                                    showNumber={(detailsList?.data?.proposed_amount) / 1000000}
                                    headerTitle={t("ConfirmDialog.proposed_amount")}
                                    unitTitle={t("ConfirmDialog.unit")}
                                />
                                <NumberShowBox
                                    showNumber={detailsList?.data?.sakht_period}
                                    headerTitle={t("ConfirmDialog.sakht_period")}
                                    unitTitle={t("ConfirmDialog.sakht_period_day")}
                                />
                                <NumberShowBox
                                    showNumber={detailsList?.data?.tanafos_period}
                                    headerTitle={t("ConfirmDialog.tanafos_period")}
                                    unitTitle={t("ConfirmDialog.tanafos_period_month")}
                                />
                                {renderCustomAccordions()}
                            </>
                        }
                        <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]*",
                                    }}
                                    variant="outlined"
                                    value={formik.values.approved_amount}
                                    onChange={handleAmountChange}
                                    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>
                                <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_img"
                                            fileType={fileTypesA}
                                            fileName={fileNamesA}
                                            imageAlt={t("app_name")}
                                            imageSize={[250, 150]}
                                            setShowAddIcon={setShowAddIconA}
                                            showAddIcon={showAddIconA}
                                            onBlur={() => formik.handleBlur("first_img")}
                                            error={
                                                formik.touched.first_img &&
                                                Boolean(formik.errors.first_img)
                                            }
                                        />
                                        <FormHelperText
                                            error={Boolean(formik.errors.first_img)}
                                        >
                                            {formik.touched.first_img && formik.errors.first_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_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_img")}
                                            error={
                                                formik.touched.second_img &&
                                                Boolean(formik.errors.second_img)
                                            }
                                        />
                                        <FormHelperText
                                            error={Boolean(formik.errors.second_img)}
                                        >
                                            {formik.touched.second_img && formik.errors.second_img}
                                        </FormHelperText>
                                    </Grid>
                                </Grid>
                            </Stack>
                        </Stack>
                    </Grid>
                    <Grid item xs={6}>
                        <Stack sx={{
                            display: hasImageShown ? 'flex' : 'none',
                            alignItems: 'center',
                            gap: 0.5,
                            justifyContent: 'center'
                        }}>
                            <ImageContent imageLink={imageLink} isSkeleton={isSkeleton} setIsSkeleton={setIsSkeleton}/>
                        </Stack>
                    </Grid>
                </Grid>
            </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 || !formik.dirty || !formik.isValid}>
                    {t("ConfirmDialog.button-confirm")}
                </Button>
            </DialogActions>
        </>
    )

}
export default ConfirmContent