import { useEffect, useMemo, useState } from "react";
import { Box, Button, Dialog, DialogActions, Stack, Typography } from "@mui/material";
import DataTableWithAuth from "@/core/components/DataTableWithAuth";
import Toolbar from "./Toolbar";
import RowActions from "./RowActions";
import { GET_FAST_REACT_COMPLAINTS } from "@/core/utils/routes";
import useProvinces from "@/lib/hooks/useProvince";
import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency";
import { usePermissions } from "@/lib/hooks/usePermissions";
import { useAuth } from "@/lib/contexts/auth";
import useEdaratLists from "@/lib/hooks/useEdaratLists";
import DescriptionForm from "./RowActions/DescriptionDialog";
import LocationForm from "./RowActions/LocationDialog";
import moment from "jalali-moment";

const ComplaintListTable = ({ open, setOpen, mutate }) => {
    const { data: userPermissions } = usePermissions();
    const hasCountryPermission = userPermissions?.includes("show-fast-react");
    const { user } = useAuth();
    const columns = useMemo(() => {
        const dynamicColumns = {
            header: "استان",
            id: "road_observeds__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_fa}</>,
        };
        return [
            {
                accessorKey: "id",
                header: "کد یکتا",
                id: "road_observeds__id",
                enableColumnFilter: true,
                datatype: "text",
                filterMode: "equals",
                sortDescFirst: false,
                columnFilterModeOptions: ["equals", "contains"],
                grow: false,
                size: 100,
            },
            ...(hasCountryPermission ? [dynamicColumns] : []),
            {
                header: "اداره",
                id: "road_observeds__edarate_shahri_id",
                enableColumnFilter: true,
                datatype: "numeric",
                filterMode: "equals",
                dependencyId: hasCountryPermission ? "road_observeds__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: ({ row }) => <>{row.original.edarate_shahri_name_fa}</>,
            },
            {
                header: "اطلاعات ثبت‌ شده در سامانه سوانح",
                id: "fkInfo",
                enableColumnFilter: false,
                enableSorting: false,
                grow: false,
                size: 50,
                columns: [
                    {
                        accessorKey: "fk_RegisteredEventMessage",
                        header: "کد سوانح",
                        id: "fk_RegisteredEventMessage",
                        enableColumnFilter: true,
                        datatype: "text",
                        filterMode: "equals",
                        sortDescFirst: false,
                        columnFilterModeOptions: ["equals", "contains"],
                        grow: false,
                        size: 100,
                    },
                    {
                        accessorKey: "Title",
                        header: "موضوع گزارش",
                        id: "Title",
                        enableColumnFilter: false,
                        datatype: "text",
                        filterMode: "equals",
                        sortDescFirst: false,
                        columnFilterModeOptions: ["equals", "contains"],
                        grow: false,
                        size: 100,
                    },
                    {
                        accessorKey: "FeatureTypeTitle",
                        header: "نوع گزارش",
                        id: "FeatureTypeTitle",
                        enableColumnFilter: false,
                        datatype: "text",
                        filterMode: "equals",
                        sortDescFirst: false,
                        columnFilterModeOptions: ["equals", "contains"],
                        grow: false,
                        size: 100,
                    },
                    {
                        accessorKey: "Description",
                        header: "توضیح گزارش",
                        id: "Description",
                        enableColumnFilter: false,
                        datatype: "text",
                        filterMode: "equals",
                        sortDescFirst: false,
                        columnFilterModeOptions: ["equals", "contains"],
                        grow: false,
                        size: 100,
                        muiTableBodyCellProps: {
                            sx: {
                                borderLeft: "1px solid #e1e1e1",
                                py: 0,
                                "&:first-of-type": {
                                    borderLeft: "unset",
                                },
                            },
                        },
                        Cell: ({ renderedCellValue }) => {
                            if (renderedCellValue) {
                                return (
                                    <Stack alignItems={"center"} justifyContent={"center"}>
                                        <DescriptionForm description={renderedCellValue} title={"توضیح گزارش"} />
                                    </Stack>
                                );
                            }
                            return <Typography variant="body2">-</Typography>;
                        },
                    },
                    {
                        header: "موقعیت",
                        id: "location",
                        enableColumnFilter: false,
                        enableSorting: false,
                        datatype: "array",
                        grow: false,
                        size: 100,
                        muiTableBodyCellProps: {
                            sx: {
                                borderLeft: "1px solid #e1e1e1",
                                py: 0,
                                "&:first-of-type": {
                                    borderLeft: "unset",
                                },
                            },
                        },
                        Cell: ({ row }) => {
                            return (
                                <Stack alignItems={"center"} justifyContent={"center"}>
                                    <LocationForm start_lat={row.original.lat} start_lng={row.original.lng} />
                                </Stack>
                            );
                        },
                    },
                    {
                        accessorKey: "MobileForSendEventSms",
                        header: "شماره تماس گیرنده",
                        id: "MobileForSendEventSms",
                        enableColumnFilter: false,
                        datatype: "text",
                        filterMode: "equals",
                        sortDescFirst: false,
                        columnFilterModeOptions: ["equals", "contains"],
                        grow: false,
                        size: 100,
                    },
                    {
                        accessorFn: (row) =>
                            moment(row.StartTime_DateTime, "M/D/YYYY h:mm:ss A")
                                .locale("fa")
                                .format("HH:mm | yyyy/MM/DD"),
                        header: "تاریخ ثبت",
                        id: "StartTime_DateTime",
                        enableColumnFilter: false,
                        datatype: "date",
                        filterMode: "between",
                        grow: false,
                        size: 100,
                    },
                ],
            },
        ];
    }, []);

    return (
        <Dialog onClose={() => setOpen(false)} open={open} fullWidth maxWidth={"xl"}>
            {open && (
                <Box sx={{ p: 1, border: 1, borderColor: "divider", borderRadius: 1 }}>
                    <DataTableWithAuth
                        need_filter={true}
                        table_title={"لیست شکایات"}
                        columns={columns}
                        sorting={[{ id: "fk_RegisteredEventMessage", desc: true }]}
                        table_url={GET_FAST_REACT_COMPLAINTS}
                        page_name={"fastReactComplaint"}
                        table_name={"fastReactComplaintList"}
                        TableToolbar={Toolbar}
                        enableRowActions
                        positionActionsColumn={"last"}
                        RowActions={(props) => <RowActions {...props} mutateParentTable={mutate} />}
                    />
                </Box>
            )}
            <DialogActions>
                <Button variant={"outlined"} color={"secondary"} onClick={() => setOpen(false)}>
                    بستن
                </Button>
            </DialogActions>
        </Dialog>
    );
};
export default ComplaintListTable;
