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

const createColumns = (sub_items) => {
    const dynamicColumns =
        sub_items?.map((sub_item) => ({
            accessorKey: `sub_item_${sub_item.sub_item}`,
            header: `${sub_item.sub_item_str}`,
            id: `sub_item_${sub_item.sub_item}`,
            columns: [
                {
                    accessorKey: `sub_item_${sub_item.sub_item}_count`,
                    header: "تعداد اقدام",
                    id: `sub_item_${sub_item.sub_item}_count`,
                    enableColumnFilter: false,
                    enableSorting: false,
                    datatype: "text",
                    grow: false,
                    muiTableBodyCellProps: {
                        sx: {
                            textAlign: "center",
                            borderLeft: "1px solid #e1e1e1",
                            py: 0,
                            "&:first-of-type": {
                                borderLeft: "unset",
                            },
                        },
                    },
                    size: 50,
                    Cell: ({ renderedCellValue }) => {
                        return (renderedCellValue / 1).toLocaleString();
                    },
                },
                {
                    accessorKey: `sub_item_${sub_item.sub_item}_sum`,
                    header: `مجموع (${sub_item.sub_item_unit})`,
                    id: `sub_item_${sub_item.sub_item}_sum`,
                    enableColumnFilter: false,
                    enableSorting: false,
                    datatype: "text",
                    muiTableBodyCellProps: {
                        sx: {
                            textAlign: "center",
                            borderLeft: "1px solid #e1e1e1",
                            py: 0,
                            "&:first-of-type": {
                                borderLeft: "unset",
                            },
                        },
                    },
                    grow: false,
                    size: 50,
                    Cell: ({ renderedCellValue }) => {
                        return (renderedCellValue / 1).toLocaleString();
                    },
                },
            ],
        })) || [];

    return [
        {
            accessorKey: "edare_name",
            header: "اداره",
            id: "edare_name",
            enableColumnFilter: false,
            enableSorting: false,
            datatype: "text",
            grow: false,
            size: 50,
        },
        {
            header: "موارد اقدام شده فعالیت روزانه",
            enableColumnFilter: false,
            id: "subItems",
            enableSorting: false,
            datatype: "text",
            grow: false,
            size: 50,
            columns: [...dynamicColumns],
        },
    ];
};

const SubItemsReports = () => {
    const [data, setData] = useState(null);
    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,
        item: 1,
    };
    const defaultFilter = [
        { value: `${defaultValues.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" },
        { value: `${defaultValues.item}`, datatype: "numeric", id: "item", 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}`);
        params.set("item", `${data.item}`);
        setSpecialFilter([
            { value: `${data.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" },
            { value: `${data.item}`, datatype: "numeric", id: "item", 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_SUB_ITEM}?${params}`);
                const result = response.data.data;
                const nationalReport = {
                    edare_name: "کل کشور",
                };

                result.sub_items.forEach((subItem) => {
                    const nationalReportForSubItem = result.activities.find(
                        (report) => report.p === -1 && report.t === subItem.sub_item
                    );
                    nationalReport[`sub_item_${subItem.sub_item}_count`] = nationalReportForSubItem
                        ? nationalReportForSubItem.c
                        : 0;
                    nationalReport[`sub_item_${subItem.sub_item}_sum`] = nationalReportForSubItem
                        ? nationalReportForSubItem.s
                        : 0;
                });

                setData({
                    data: [
                        nationalReport,
                        ...result.provinces.map((province) => {
                            const filteredReports = result.activities.filter((report) => report.p === province.id);
                            const rowData = {
                                edare_name: province.name_fa,
                            };

                            result.sub_items.forEach((subItem) => {
                                const reportForItem = filteredReports.find((report) => report.t === subItem.sub_item);
                                rowData[`sub_item_${subItem.sub_item}_count`] = reportForItem ? reportForItem.c : 0;
                                rowData[`sub_item_${subItem.sub_item}_sum`] = reportForItem ? reportForItem.s : 0;
                            });

                            return rowData;
                        }),
                    ],
                    columns: createColumns(result.sub_items),
                    filters: data,
                });
            } catch (e) {}
        } else {
            try {
                params.set("province_id", `${data.province_id}`);
                const response = await requestServer(`${GET_CITY_ACTIVITY_PER_SUB_ITEM}?${params}`);
                const result = response.data.data;
                const nationalReport = {
                    edare_name: "کل استان",
                };

                result.sub_items.forEach((subItem) => {
                    const nationalReportForSubItem = result.activities.find(
                        (report) => report.ci === -1 && report.t === subItem.sub_item
                    );
                    nationalReport[`sub_item_${subItem.sub_item}_count`] = nationalReportForSubItem
                        ? nationalReportForSubItem.c
                        : 0;
                    nationalReport[`sub_item_${subItem.sub_item}_sum`] = nationalReportForSubItem
                        ? nationalReportForSubItem.s
                        : 0;
                });

                setData({
                    data: [
                        nationalReport,
                        ...result.edarateShahri.map((edare) => {
                            const filteredReports = result.activities.filter((report) => report.ci === edare.id);
                            const rowData = {
                                edare_name: edare.name_fa,
                            };

                            result.sub_items.forEach((subItem) => {
                                const reportForItem = filteredReports.find((report) => report.t === subItem.sub_item);
                                rowData[`sub_item_${subItem.sub_item}_count`] = reportForItem ? reportForItem.c : 0;
                                rowData[`sub_item_${subItem.sub_item}_sum`] = reportForItem ? reportForItem.s : 0;
                            });

                            return rowData;
                        }),
                    ],
                    columns: createColumns(result.sub_items),
                    filters: data,
                });
            } catch (e) {
                console.log(e);
            }
        }
    };

    useEffect(() => {
        if (!userPermissions) return;
        onSearchSubmit(defaultValues);
    }, [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(),
        item: yup.number().required("آیتم مورد نظر را وارد کنید!!!"),
    });

    const { control, handleSubmit } = useForm({
        defaultValues,
        resolver: yupResolver(validationSchema),
        mode: "all",
    });
    return (
        <Stack spacing={1}>
            <PageTitle title={"کارتابل گزارش تعداد فعالیت ها به تفکیک موارد اقدام شده"} />
            <SearchReportList
                control={control}
                hasProvincesPermission={hasProvincesPermission}
                handleSubmit={handleSubmit}
                onSearchSubmit={onSearchSubmit}
            />
            {!data ? <LinearProgress /> : <SubItemsList specialFilter={specialFilter} data={data} />}
        </Stack>
    );
};
export default SubItemsReports;
