"use client";
import PageTitle from "@/core/components/PageTitle";
import { LinearProgress, Stack, Typography } from "@mui/material";
import SearchReportList from "./Search";
import { useEffect, useState } from "react";
import ReportLists from "./ReportLists";
import useRequest from "@/lib/hooks/useRequest";
import { GET_CITY_ACTIVITY_PER_ITEM, GET_PROVINCE_ACTIVITY_PER_ITEM } from "@/core/utils/routes";
import useRoadItemGetItems from "@/lib/hooks/useRoadItemGetItems";
import moment from "jalali-moment";
import * as yup from "yup";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import { usePermissions } from "@/lib/hooks/usePermissions";
import { useAuth } from "@/lib/contexts/auth";

const ReportPage = () => {
    const [data, setData] = useState(null);
    const { itemsList, loadingItemsList, errorItemsList } = useRoadItemGetItems();
    const { data: userPermissions } = usePermissions();

    const { user } = useAuth();
    const requestServer = useRequest();
    const hasProvincesPermission = userPermissions?.includes("show-road-item-supervise-cartable");

    const defaultValues = {
        from_date: moment(new Date()).format("YYYY-MM-DD"),
        date_to: moment(new Date()).format("YYYY-MM-DD"),
        province_id: hasProvincesPermission ? "-1" : user.province_id,
    };
    const defaultFilter = [
        { value: `${defaultValues.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" },
        { value: `${defaultValues.from_date}`, datatype: "date", id: "from_date", fn: "between" },
        { value: `${defaultValues.date_to}`, datatype: "date", id: "date_to", fn: "between" },
    ];
    const [specialFilter, setSpecialFilter] = useState(defaultFilter);

    const onSearchSubmit = async (data) => {
        const params = new URLSearchParams();
        params.set("from_date", `${data.from_date}`);
        params.set("date_to", `${data.date_to}`);
        setSpecialFilter([
            { value: `${data.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" },
            { value: `${data.from_date}`, datatype: "date", id: "from_date", fn: "between" },
            { value: `${data.date_to}`, datatype: "date", id: "date_to", fn: "between" },
        ]);
        if (data.province_id === "-1") {
            try {
                const response = await requestServer(`${GET_PROVINCE_ACTIVITY_PER_ITEM}?${params}`);
                const result = response.data.data;
                const nationalReport = {
                    edare_name: "کل کشور",
                    sum: result.activities.length
                        ? result.activities
                              .filter((report) => report.p === -1)
                              .reduce((acc, report) => acc + (report.s || 0), 0)
                        : 0,
                };
                itemsList.forEach((item) => {
                    const nationalReportForItem = result.activities.find(
                        (report) => report.p === -1 && report.i === item.id
                    );
                    nationalReport[`item_${item.id}`] = nationalReportForItem ? nationalReportForItem.s : 0;
                });

                setData({
                    data: [
                        nationalReport,
                        ...result.provinces.map((province) => {
                            const filteredReports = result.activities.filter((report) => report.p === province.id);
                            const sum = filteredReports.reduce((acc, report) => acc + (report.s || 0), 0);
                            const rowData = {
                                edare_name: province.name_fa,
                                sum,
                            };
                            itemsList.forEach((item) => {
                                const reportForItem = filteredReports.find((report) => report.i === item.id);
                                rowData[`item_${item.id}`] = reportForItem ? reportForItem.s : 0;
                            });
                            return rowData;
                        }),
                    ],
                    filters: data,
                });
            } catch (e) {}
        } else {
            try {
                params.set("province_id", `${data.province_id}`);
                const response = await requestServer(`${GET_CITY_ACTIVITY_PER_ITEM}?${params}`);
                const result = response.data.data;
                const nationalReport = {
                    edare_name: "کل استان",
                    sum: result.activities.length
                        ? result.activities
                              .filter((report) => report.c === -1)
                              .reduce((acc, report) => acc + (report.s || 0), 0)
                        : 0,
                };

                itemsList.forEach((item) => {
                    const nationalReportForItem = result.activities.find(
                        (report) => report.c === -1 && report.i === item.id
                    );
                    nationalReport[`item_${item.id}`] = nationalReportForItem ? nationalReportForItem.s : 0;
                });

                setData({
                    data: [
                        nationalReport,
                        ...result.edarateShahri.map((edare) => {
                            const filteredReports = result.activities.filter((report) => report.c === edare.id);
                            const sum = filteredReports.reduce((acc, report) => acc + (report.s || 0), 0);

                            const rowData = {
                                edare_name: edare.name_fa,
                                sum,
                            };

                            itemsList.forEach((item) => {
                                const reportForItem = filteredReports.find((report) => report.i === item.id);
                                rowData[`item_${item.id}`] = reportForItem ? reportForItem.s : 0;
                            });

                            return rowData;
                        }),
                    ],
                    filters: data,
                });
            } catch (e) {}
        }
    };

    useEffect(() => {
        if (!userPermissions) return;
        if (itemsList.length === 0) return;
        onSearchSubmit(defaultValues);
    }, [itemsList, userPermissions]);

    const validationSchema = yup.object().shape({
        from_date: yup
            .string()
            .required("تاریخ شروع الزامی است!")
            .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ شروع الزامی است!")
            .test("is-valid-date", "تاریخ شروع معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()),
        date_to: yup
            .string()
            .required("تاریخ پایان الزامی است!")
            .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ پایان الزامی است!")
            .test("is-valid-date", "تاریخ پایان معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()),
        province_id: yup.string().nullable(),
    });

    const { control, handleSubmit } = useForm({
        defaultValues,
        resolver: yupResolver(validationSchema),
        mode: "onBlur",
    });
    return (
        <Stack spacing={1}>
            <PageTitle title={"کارتابل گزارش تعداد فعالیت ها به تفکیک آیتم"} />
            <SearchReportList
                control={control}
                hasProvincesPermission={hasProvincesPermission}
                handleSubmit={handleSubmit}
                onSearchSubmit={onSearchSubmit}
            />
            {!data || loadingItemsList ? (
                <LinearProgress />
            ) : errorItemsList ? (
                <Typography color={"error.main"} textAlign={"center"}>
                    خطا در دریافت اطلاعات!!!
                </Typography>
            ) : (
                <ReportLists specialFilter={specialFilter} data={data} itemsList={itemsList} />
            )}
        </Stack>
    );
};
export default ReportPage;
