import {useTranslations} from "next-intl";
import {useRouter} from "next/router";
import {useState} from "react";
import useRequest from "@/lib/app/hooks/useRequest";
import usePrint from "@/lib/app/hooks/usePrint";
import {Button, CircularProgress} from "@mui/material";
import PrintIcon from "@mui/icons-material/Print";
import {GET_PASSENGER_BOSS} from "@/core/data/apiRoutes";

const PrintFormA = () => {
    const t = useTranslations();
    const router = useRouter()
    const [loading, setLoading] = useState(false)
    const requestServer = useRequest({auth: true, pending: false, success: {notification: {show: false}}})
    const {setPrintPage, setPrintTitle} = usePrint()

    const filterRequest = async (filterArr) => {
        setLoading(true);

        const requests = filterArr.map(async (item) => {
            try {
                const params = new URLSearchParams();
                params.set("start", '0');
                params.set("filters", JSON.stringify([item]));
                params.set("sorting", '[]');

                const response = await requestServer(`${GET_PASSENGER_BOSS}?${params}`, 'get');
                const _chunkSize = 6;
                const _data = response.data.data;
                const chunk = Array.from({length: Math.ceil(_data.length / _chunkSize)}, (v, i) =>
                    _data.slice(i * _chunkSize, i * _chunkSize + _chunkSize)
                );
                return chunk;
            } catch (error) {
                setLoading(false);
                throw error; // Propagate the error
            }
        });

        try {
            const chunks = await Promise.all(requests);
            setLoading(false);
            return chunks.flat(); // Flatten the chunks into a single array
        } catch (error) {
            console.error("Error processing requests:", error);
            throw error;
        }
    };

    const clickHandler = async () => {
        try {
            const chunks = await filterRequest([
                {
                    id: "vehicle_type",
                    value: "اتوبوس",
                    fn: "contains",
                    datatype: "text",
                },
                {
                    id: "vehicle_type",
                    value: "مینی بوس",
                    fn: "contains",
                    datatype: "text",
                },
            ]);
            setPrintPage(chunks.length);
            setPrintTitle(t('PassengerBoss.print_form_a'));
            sessionStorage.setItem('form-a-print', JSON.stringify(chunks));
            router.push('/dashboard/passenger-boss/prints/form-a');
        } catch (error) {
            console.error("Error in clickHandler:", error);
        }
    };
    return (
        <Button
            color="primary"
            variant="contained"
            size="small"
            disabled={loading}
            sx={{textTransform: "unset", alignSelf: "center"}}
            startIcon={loading ? <CircularProgress size={18} color="inherit"/> : <PrintIcon/>}
            onClick={clickHandler}
        >
            {t("PassengerBoss.print_form_a")}
        </Button>
    )
}

export default PrintFormA