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

const ConfirmContent = ({rowId, mutate, setOpenConfirmDialog, handleSizeChangeClick}) => {
    const t = useTranslations();
    const [selectedImage, setSelectedImage] = useState("");
    const [fileType, setfileType] = useState(null);
    const [fileName, setfileName] = useState(null);
    const [showAddIcon, setShowAddIcon] = useState(true);
    const requestServer = useRequest({auth: true, notification: false});
    const [attachmentsData, setAttachmentsData] = useState([]);
    const [accordionStates, setAccordionStates] = useState([]);
    const [hasAccordionOpened, setHasAccordionOpened] = useState([]);
    const {update_notification} = useNotification();
    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);
    const [checked, setChecked] = useState(false);

    useEffect(() => {
        requestServer(`${GET_TRANSPORTATION_ASSISTANCE_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);
            })
            .catch(() => {
            }).finally(() => {
            setLoading(false);
        });
    }, []);

    useEffect(() => {
        if (attachmentsData.length !== 0) {
            const booleanData = Array.from({length: attachmentsData.length}, () => false);
            setAccordionStates(booleanData);
            setHasAccordionOpened(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 newHasAccordionOpened = [...hasAccordionOpened];
            newHasAccordionOpened[index] = true;
            setHasAccordionOpened(newHasAccordionOpened);
        }
    };


    const validationSchema = Yup.object().shape({
        confirm_img: Yup.mixed().notRequired(t("ConfirmDialog.approved_amount_error"))
            .test('fileSize', `${t("TransportationAssistance.upload_file_unit")}`, (value) => {
                if (!value) return true
                return value.size <= 2 * 1024 * 1024;
            })
            .test('fileType', `${t("TransportationAssistance.upload_file_format")}`, (value) => {
                if (!value) return true
                const allowedTypes = ['image/jpg', 'image/jpeg', 'image/png', 'application/pdf'];
                return allowedTypes.includes(value.type);
            })
    })

    const formik = useFormik({
        initialValues: {
            description: "",
            confirm_img: null
        }, validationSchema,
        onSubmit: (values, {setSubmitting}) => {
            const formData = new FormData();
            if (values.description !== "") formData.append("expert_description", values.description);
            if (values.confirm_img != null) {
                const attachments = [
                    {
                        title: "فایل ضمیمه کارتابل بررسی وام های تبصره 18",
                        file: values.confirm_img
                    }
                ];
                attachments.forEach((attachment, index) => {
                    formData.append(`attachment[${index}][title]`, attachment.title);
                    formData.append(`attachment[${index}][file]`, attachment.file);
                });
            }
            requestServer(`${CONFIRM_TRANSPORTATION_ASSISTANCE}/${rowId}`, 'post', {
                data: formData,
                notification: true
            }).then((response) => {
                setOpenConfirmDialog(false)
                mutate()
                update_notification()
            }).catch(() => {
            }).finally(() => {
                setSubmitting(false);
            });
        },
    });

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

    const handleUploadChange = (event) => {
        const uploadedFile = event.target?.files?.[0];
        if (uploadedFile) {
            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).then(() => {
                formik.setFieldTouched("confirm_img", true);
            })
            setShowAddIcon(false);
        }
    };
    const handleCheckboxChange = (event) => {
        setChecked(event.target.checked);
    };

    const renderCustomAccordions = () => {
        if (attachmentsData) {
            return attachmentsData.map((file, index) => (
                <CustomAccordion
                    key={index}
                    title={`${file.title}`}
                    hasOpened={accordionStates[index]}
                    hasAccordionOpened={hasAccordionOpened[index]}
                    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?.approved_amount) / 1000000}
                                    headerTitle={t("ConfirmDialog.approved_amount_title")}
                                    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>
                                <Typography>{t("UploadSystem.upload_file")}{t("UploadSystem.optional")}</Typography>
                                <UploadSystem
                                    selectedImage={selectedImage}
                                    handleUploadChange={handleUploadChange}
                                    setselectedImage={setSelectedImage}
                                    setFieldValue={formik.setFieldValue}
                                    fieldname="confirm_img"
                                    fileType={fileType}
                                    fileName={fileName}
                                    imageAlt={t("app_name")}
                                    imageSize={[250, 150]}
                                    setShowAddIcon={setShowAddIcon}
                                    showAddIcon={showAddIcon}
                                    onBlur={() => formik.handleBlur("confirm_img")}
                                    error={
                                        formik.touched.confirm_img &&
                                        Boolean(formik.errors.confirm_img)
                                    }
                                />
                                <FormHelperText error={Boolean(formik.errors.confirm_img)}>
                                    {formik.touched.confirm_img && formik.errors.confirm_img}
                                </FormHelperText>
                            </Stack>
                            <Stack>
                                <FormControlLabel
                                    control={
                                        <Checkbox
                                            checked={checked}
                                            onChange={handleCheckboxChange}
                                            color="primary"
                                        />
                                    }
                                    label={t("TransportationAssistance.confirm_text")}
                                />
                            </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.isValid ||
                            hasAccordionOpened.some((opened) => !opened) || !checked}
                >
                    {t("ConfirmDialog.button-confirm")}
                </Button>
            </DialogActions>
        </>
    )

}
export default ConfirmContent