"use client";
import DataTableWithAuth from "@/core/components/DataTableWithAuth";
import { GET_ROAD_MISSIONS_CONTROL_LIST } from "@/core/utils/routes";
import { Box, Stack } from "@mui/material";
import moment from "jalali-moment";
import { useMemo } from "react";
import MachinesDialog from "./RowActions/Machines";
import RowActions from "./RowActions";
import RahdaranDialog from "./RowActions/Rahdaran";
import useProvinces from "@/lib/hooks/useProvince";
import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency";
import useCities from "@/lib/hooks/useCities";

const ControlList = () => {
    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,
                size: 100,
            },
            ...[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: "station_name",
                header: "راهدارخانه",
                id: "station_name",
                enableColumnFilter: false,
                datatype: "text",
                filterMode: "equals",
                grow: false,
                size: 100,
            },
            {
                accessorFn: (row) =>
                    row.type == 1
                        ? moment(row.start_date).locale("fa").format("HH:mm | yyyy/MM/DD")
                        : moment(row.start_date).locale("fa").format("yyyy/MM/DD"),
                header: "تاریخ شروع",
                id: "start_date",
                enableColumnFilter: true,
                datatype: "date",
                filterMode: "between",
                grow: false,
                size: 100,
            },
            {
                accessorFn: (row) =>
                    row.type == 1
                        ? moment(row.end_date).locale("fa").format("HH:mm | yyyy/MM/DD")
                        : moment(row.end_date).locale("fa").format("yyyy/MM/DD"),
                header: "تاریخ پایان",
                id: "end_date",
                enableColumnFilter: true,
                datatype: "date",
                filterMode: "between",
                grow: false,
                size: 100,
            },
            {
                header: "خودرو",
                id: "cmmsMachines__machine_code",
                enableColumnFilter: true,
                datatype: "text",
                filterMode: "contains",
                enableSorting: false,
                columnFilterModeOptions: ["equals", "contains"],
                grow: false,
                size: 100,
                muiTableBodyCellProps: {
                    sx: {
                        borderLeft: "1px solid #e1e1e1",
                        py: 0,
                        "&:first-of-type": {
                            borderLeft: "unset",
                        },
                    },
                },
                Cell: ({ renderedCellValue, row }) => {
                    return (
                        <Stack alignItems={"center"} justifyContent={"center"}>
                            <MachinesDialog rowId={row.original.id} />
                        </Stack>
                    );
                },
            },
            {
                header: "افراد",
                id: "rahdaran__code",
                enableColumnFilter: true,
                enableSorting: false,
                datatype: "text",
                filterMode: "contains",
                columnFilterModeOptions: ["equals", "contains"],
                grow: false,
                size: 100,
                muiTableBodyCellProps: {
                    sx: {
                        borderLeft: "1px solid #e1e1e1",
                        py: 0,
                        "&:first-of-type": {
                            borderLeft: "unset",
                        },
                    },
                },
                Cell: ({ renderedCellValue, row }) => {
                    return (
                        <Stack alignItems={"center"} justifyContent={"center"}>
                            <RahdaranDialog rowId={row.original.id} />
                        </Stack>
                    );
                },
            },
            {
                accessorFn: (row) =>
                    row.start_time ? moment(row.start_time).locale("fa").format("HH:mm | yyyy/MM/DD") : null,
                header: "تاریخ خروج",
                id: "start_time",
                enableColumnFilter: true,
                datatype: "date",
                filterMode: "between",
                grow: false,
                size: 100,
            },
        ];
    }, []);

    return (
        <>
            <Box sx={{ p: 1, border: 1, borderColor: "divider", borderRadius: 1 }}>
                <DataTableWithAuth
                    need_filter={true}
                    columns={columns}
                    sorting={[{ id: "id", desc: true }]}
                    table_url={GET_ROAD_MISSIONS_CONTROL_LIST}
                    page_name={"roadMissionsControl"}
                    table_name={"roadMissionsControlList"}
                    enableRowActions
                    positionActionsColumn={"first"}
                    RowActions={RowActions}
                />
            </Box>
        </>
    );
};
export default ControlList;
