"use client";
import CustomSelectByDependency from "@/core/components/FilterDrawer/fieldsType/CustomSelectByDependency";
import PageTitle from "@/core/components/PageTitle";
import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure";
import groupByEdareAxisStep from "@/core/utils/groupByEdareAxisStep";
import groupByProvinceAxisStep from "@/core/utils/groupByProvinceAxisStep";
import isArrayEmpty from "@/core/utils/isArrayEmpty";
import {
    GET_ROAD_SAFETY_CITY_ACTIVITY_CONSTRUCTION_ACTIVITY_REPORT,
    GET_ROAD_SAFETY_PROVINCE_ACTIVITY_CONSTRUCTION_ACTIVITY_REPORT,
} from "@/core/utils/routes";
import { useAuth } from "@/lib/contexts/auth";
import { usePermissions } from "@/lib/hooks/usePermissions";
import useProvinces from "@/lib/hooks/useProvince";
import useRequest from "@/lib/hooks/useRequest";
import { LinearProgress, Stack } from "@mui/material";
import { useEffect, useMemo, useState } from "react";
import ReportLists from "./ReportLists";

const ReportConstructionActivityPage = () => {
    const { data: userPermissions } = usePermissions();
    const hasProvincesPermission = userPermissions.includes("show-safety-and-privacy-operator-cartable");
    const { user } = useAuth();
    const requestServer = useRequest();
    const [data, setData] = useState(null);
    const [isLoading, setLoading] = useState(true);

    const defaultValues = useMemo(
        () => [
            {
                header: "استان",
                id: "province_id",
                filterMode: "equals",
                datatype: "numeric",
                value: hasProvincesPermission ? "" : user.province_id,
                enable: hasProvincesPermission,
                SelectComponent: (props) => {
                    const { provinces, errorProvinces, loadingProvinces } = useProvinces();
                    const getSelectOptions = useMemo(() => {
                        if (loadingProvinces) {
                            return [{ value: "loading", label: "در حال بارگذاری..." }];
                        }
                        if (errorProvinces) {
                            return [{ value: "error", label: "خطا در بارگذاری" }];
                        }
                        return [
                            { value: "", label: "کل کشور" },
                            ...provinces.map((province) => ({
                                value: province.id,
                                label: province.name_fa,
                            })),
                        ];
                    }, [provinces, errorProvinces, loadingProvinces]);
                    return (
                        <CustomSelectByDependency
                            {...props}
                            value={loadingProvinces ? "loading" : props.filterParameters.value}
                            selectOption={getSelectOptions}
                        />
                    );
                },
            },
            {
                header: "مورد",
                id: "info_id",
                filterMode: "equals",
                datatype: "numeric",
                value: "89",
                enable: false,
            },
            {
                header: "تاریخ ثبت",
                id: "created_at",
                filterMode: "between",
                datatype: "date",
                value: ["", ""],
                enable: true,
            },
            {
                header: "تاریخ بازدید",
                id: "activity_date_time",
                filterMode: "between",
                datatype: "date",
                value: ["", ""],
                enable: true,
            },
            {
                header: "تاریخ بارگذاری مستندات",
                id: "judiciary_document_upload_date",
                filterMode: "between",
                datatype: "date",
                value: ["", ""],
                enable: true,
            },
            {
                header: "تاریخ اقدام",
                id: "action_date",
                filterMode: "between",
                datatype: "date",
                value: ["", ""],
                enable: true,
            },
        ],
        [hasProvincesPermission, user.province_id]
    );

    const [filterData, setFilterData] = useState(
        defaultValues.reduce((acc, item) => {
            acc[item.id] = item;
            return acc;
        }, {})
    );

    useEffect(() => {
        const fetchData = async () => {
            try {
                setLoading(true);
                const filters = DataTableFilterDataStructure(filterData, isArrayEmpty);
                const params = new URLSearchParams();
                params.set("filters", JSON.stringify(filters || []));
                if (filterData.province_id.value === "") {
                    try {
                        const response = await requestServer(
                            `${GET_ROAD_SAFETY_PROVINCE_ACTIVITY_CONSTRUCTION_ACTIVITY_REPORT}?${params.toString()}`
                        );

                        const result = response.data.data;
                        const grouped = groupByProvinceAxisStep(result.activities);

                        const nationalReportForItem = grouped[-1];
                        const nationalReport = {
                            edare_name: "کل کشور",
                            ...nationalReportForItem,
                        };

                        setData([
                            nationalReport,
                            ...result.provinces.map((province) => {
                                const filteredReports = grouped[province.id];
                                return {
                                    ...filteredReports,
                                    edare_name: province.name_fa,
                                };
                            }),
                        ]);
                    } catch (e) {
                        console.log(e);
                    }
                } else {
                    params.set("province_id", filterData.province_id.value);
                    try {
                        const response = await requestServer(
                            `${GET_ROAD_SAFETY_CITY_ACTIVITY_CONSTRUCTION_ACTIVITY_REPORT}?${params.toString()}`
                        );
                        const result = response.data.data;
                        const grouped = groupByEdareAxisStep(result.activities);

                        const nationalReportForItem = grouped[-1];
                        const nationalReport = {
                            ...nationalReportForItem,
                            edare_name: "کل استان",
                        };
                        setData([
                            nationalReport,
                            ...result.edarateShahri.map((edare) => {
                                const filteredReports = grouped[edare.id];
                                return {
                                    edare_name: edare.name_fa,
                                    ...filteredReports,
                                };
                            }),
                        ]);
                    } catch (e) {
                        console.log(e);
                    }
                }
            } catch (error) {
                console.log(error);
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, [filterData]);

    return (
        <Stack spacing={1}>
            <PageTitle title={"گزارش بر اساس ساخت و ساز غیر مجاز"} />
            {!data ? (
                <LinearProgress />
            ) : (
                <>
                    <ReportLists
                        filterData={filterData}
                        setFilterData={setFilterData}
                        isLoading={isLoading}
                        data={data}
                    />
                </>
            )}
        </Stack>
    );
};
export default ReportConstructionActivityPage;
