"use client";
import PageTitle from "@/core/components/PageTitle";
import { LinearProgress, Stack } 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_REPORT, GET_PROVINCE_ACTIVITY_REPORT } from "@/core/utils/routes";
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 { data: userPermissions } = usePermissions();
    const { user } = useAuth();
    const requestServer = useRequest();
    const hasProvincesPermission = userPermissions?.includes("show-road-patrol-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_REPORT}?${params}`);
                const result = response.data.data;
                const nationalReportForItem = result.activities.find((report) => report.province_id === -1);
                const nationalReport = {
                    edare_name: "کل کشور",
                    ...nationalReportForItem,
                };

                setData({
                    data: [
                        nationalReport,
                        ...result.provinces.map((province) => {
                            const filteredReports = result.activities.find(
                                (report) => report.province_id === province.id
                            );
                            return {
                                ...filteredReports,
                                edare_name: province.name_fa,
                            };
                        }),
                    ],
                    filters: data,
                });
            } catch (e) {}
        } else {
            try {
                params.set("province_id", `${data.province_id}`);
                const response = await requestServer(`${GET_CITY_ACTIVITY_REPORT}?${params}`);
                const result = response.data.data;
                const nationalReportForItem = result.activities.find((report) => report.edare_id === "-1");
                const nationalReport = {
                    ...nationalReportForItem,
                    edare_name: "کل استان",
                };
                setData({
                    data: [
                        nationalReport,
                        ...result.edarateShahri.map((edare) => {
                            const filteredReports = result.activities.find((report) => report.edare_id == edare.id);
                            return {
                                edare_name: edare.name_fa,
                                ...filteredReports,
                            };
                        }),
                    ],
                    filters: data,
                });
            } catch (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(),
    });

    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 /> : <ReportLists specialFilter={specialFilter} data={data} />}
        </Stack>
    );
};
export default ReportPage;
