"use client";
import DataTableWithAuth from "@/core/components/DataTableWithAuth";
import { GET_RAHDARAN_TABLE_LIST } from "@/core/utils/routes";
import { Box } from "@mui/material";
import { useEffect, useMemo, useState } from "react";
import RowActions from "./RowActions";
import Toolbar from "./Toolbar";
import { useAuth } from "@/lib/contexts/auth";
import useProvinces from "@/lib/hooks/useProvince";
import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency";
import useEdaratLists from "@/lib/hooks/useEdaratLists";
import { usePermissions } from "@/lib/hooks/usePermissions";

const RahdaranList = () => {
    const { data: userPermissions } = usePermissions();
    const { user } = useAuth();
    const hasCountryPermission = userPermissions?.includes("manage-rahdaran-country");
    const columns = useMemo(() => {
        const provinceColumn = {
            accessorKey: "province_id",
            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: ({ row }) => <>{row.original.province_name}</>,
        };
        return [
            {
                accessorKey: "id",
                header: "کد یکتا",
                id: "id",
                enableColumnFilter: true,
                datatype: "text",
                filterMode: "equals",
                sortDescFirst: false,
                columnFilterModeOptions: ["equals", "contains"],
                grow: false,
                size: 100,
            },
            ...(hasCountryPermission ? [provinceColumn] : []),
            {
                header: "اداره",
                id: "edareh_shahri_id",
                enableColumnFilter: true,
                datatype: "numeric",
                filterMode: "equals",
                dependencyId: hasCountryPermission ? "province_id" : null,
                grow: false,
                size: 120,
                ColumnSelectComponent: (props) => {
                    const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists(
                        hasCountryPermission ? props.dependencyFieldValue.value : user.province_id
                    );
                    const [prevDependency, setPrevDependency] = useState(
                        hasCountryPermission ? props.dependencyFieldValue.value : user.province_id
                    );

                    const getColumnSelectOptions = useMemo(() => {
                        if (hasCountryPermission && props.dependencyFieldValue.value === "") {
                            return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }];
                        }
                        if (loadingEdaratList) {
                            return [{ value: "loading", label: "در حال بارگذاری..." }];
                        }
                        if (errorEdaratList) {
                            return [{ value: "error", label: "خطا در بارگذاری" }];
                        }
                        return [
                            { value: "", label: "کل ادارات" },
                            ...edaratList.map((edare) => ({
                                value: edare.id,
                                label: edare.name_fa,
                            })),
                        ];
                    }, [edaratList, loadingEdaratList, errorEdaratList]);
                    useEffect(() => {
                        if (hasCountryPermission) return;
                        if (prevDependency === props.dependencyFieldValue?.value) return;
                        props.handleChange({ ...props.filterParameters, value: "" });
                        setPrevDependency(props.dependencyFieldValue?.value);
                    }, [props.dependencyFieldValue?.value, hasCountryPermission]);
                    return (
                        <CustomSelectByDependency
                            {...props}
                            value={
                                props.dependencyFieldValue?.value === ""
                                    ? "empty"
                                    : loadingEdaratList
                                      ? "loading"
                                      : props.filterParameters.value
                            }
                            columnSelectOption={getColumnSelectOptions}
                        />
                    );
                },
                Cell: ({ renderedCellValue, row }) => <>{row.original.edareh_shahri_name}</>,
            },
            {
                accessorKey: "name",
                header: "نام و نام خانوادگی",
                id: "name",
                enableColumnFilter: true,
                datatype: "text",
                filterMode: "equals",
                columnFilterModeOptions: ["equals", "contains"],
                grow: false,
                size: 100,
            },
            {
                accessorKey: "code",
                header: "کد ملی",
                id: "code",
                enableColumnFilter: true,
                datatype: "text",
                filterMode: "equals",
                columnFilterModeOptions: ["equals", "contains"],
                grow: false,
                size: 100,
            },
            {
                accessorKey: "mobile",
                header: "شماره همراه",
                id: "mobile",
                enableColumnFilter: true,
                datatype: "text",
                filterMode: "equals",
                columnFilterModeOptions: ["equals", "contains"],
                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_RAHDARAN_TABLE_LIST}
                    page_name={"permissionTablePage"}
                    table_name={"permissionTableList"}
                    TableToolbar={Toolbar}
                    enableRowActions
                    positionActionsColumn={"last"}
                    RowActions={RowActions}
                />
            </Box>
        </>
    );
};
export default RahdaranList;
