"use client";
import DataTableWithAuth from "@/core/components/DataTableWithAuth";
import { GET_ROAD_MISSIONS_VIOLATIONS_LIST } from "@/core/utils/routes";
import { Box } from "@mui/material";
import moment from "jalali-moment";
import { useMemo } from "react";
import RowActions from "./RowActions";
import Toolbar from "./Toolbar";
import { violationsCategoryStatus } from "@/core/utils/violationsCategoryStatus";
import useProvinces from "@/lib/hooks/useProvince";
import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency";
import useCities from "@/lib/hooks/useCities";

const ViolationsList = () => {
    const columns = useMemo(
        () => {
            const dynamicColumns = {
                header: "استان",
                id: "province_id",
                enableColumnFilter: true,
                datatype: "numeric",
                filterMode: "equals",
                grow: false,
                size: 130,
                ColumnSelectComponent: (props) => {
                    const { provinces, errorProvinces, loadingProvinces } = useProvinces();
                    const getColumnSelectOptions = 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}
                            columnSelectOption={getColumnSelectOptions}
                        />
                    );
                },
                Cell: ({ renderedCellValue, row }) => {
                    return <>{row.original.province_name}</>;
                },
            };
            return [
                {
                    accessorKey: "id",
                    header: "کد یکتا",
                    id: "id",
                    enableColumnFilter: true,
                    datatype: "text",
                    filterMode: "equals",
                    columnFilterModeOptions: ["equals", "contains"],
                    grow: false,
                },
                {
                    accessorKey: "status",
                    header: "وضعیت",
                    id: "status",
                    enableColumnFilter: true,
                    datatype: "numeric",
                    filterMode: "equals",
                    sortDescFirst: true,
                    grow: false,
                    columnSelectOption: () => {
                        return violationsCategoryStatus.map((category) => ({
                            value: category.id,
                            label: category.name_fa,
                        }));
                    },
                    Cell: ({ row }) => (row.original.type === 1 ? "خروج بدون مجوز" : "عدم تحرک"),
                },
                {
                    accessorKey: "machine_code",
                    header: "کد خودرو",
                    id: "machine_code",
                    datatype: "text",
                    columnFilterModeOptions: ["equals", "contains"],
                    grow: false,
                },
                ...[dynamicColumns],
                {
                    header: "شهر",
                    id: "city_id",
                    enableColumnFilter: true,
                    datatype: "numeric",
                    filterMode: "equals",
                    dependencyId: "province_id",
                    grow: false,
                    size: 120,
                    ColumnSelectComponent: (props) => {
                        const { cityList, loadingCityList, errorCityList } = useCities(
                            props.dependencyFieldValue.value
                        );

                        const getColumnSelectOptions = useMemo(() => {
                            if (props.dependencyFieldValue.value === "") {
                                return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }];
                            }
                            if (loadingCityList) {
                                return [{ value: "loading", label: "در حال بارگذاری..." }];
                            }
                            if (errorCityList) {
                                return [{ value: "error", label: "خطا در بارگذاری" }];
                            }
                            return [
                                { value: "", label: "کل ادارات" },
                                ...cityList.map((edare) => ({
                                    value: edare.id,
                                    label: edare.name_fa,
                                })),
                            ];
                        }, [cityList, loadingCityList, errorCityList]);
                        return (
                            <CustomSelectByDependency
                                {...props}
                                value={
                                    props.dependencyFieldValue?.value === ""
                                        ? "empty"
                                        : loadingCityList
                                          ? "loading"
                                          : props.filterParameters.value
                                }
                                columnSelectOption={getColumnSelectOptions}
                            />
                        );
                    },
                    Cell: ({ row }) => <>{row.original.city_name}</>,
                },
                {
                    accessorKey: "machine",
                    header: "نام خودرو",
                    id: "machine",
                    datatype: "text",
                    columnFilterModeOptions: ["equals", "contains"],
                    grow: false,
                    Cell: ({ row }) => row.original.machine?.car_name || "-",
                },
                {
                    accessorKey: "mission_id",
                    header: "کد ماموریت",
                    id: "mission_id",
                    enableColumnFilter: false,
                    datatype: "numeric",
                    filterMode: "equals",
                    grow: false,
                    Cell: ({ row }) => row.original.mission_id || "-",
                },
                {
                    accessorKey: "request_date",
                    header: "تاریخ تخلف",
                    id: "request_date",
                    enableColumnFilter: true,
                    datatype: "date",
                    filterMode: "between",
                    grow: false,
                    Cell: ({ row }) => moment(row.original.request_date).locale("fa").format("YYYY/MM/DD"),
                },
            ];
        },
        []
    );

    return (
        <>
            <Box sx={{ p: 1, border: 1, borderColor: "divider", borderRadius: 1 }}>
                <DataTableWithAuth
                    need_filter={true}
                    columns={columns}
                    TableToolbar={Toolbar}
                    sorting={[{ id: "id", desc: true }]}
                    table_url={GET_ROAD_MISSIONS_VIOLATIONS_LIST}
                    page_name={"roadMissionsOperator"}
                    table_name={"roadMissionsViolationsList"}
                    enableRowActions
                    positionActionsColumn={"first"}
                    RowActions={RowActions}
                />
            </Box>
        </>
    );
};
export default ViolationsList;
