"use client"
import {Box, Button, Divider, Drawer, FormControl, IconButton, styled, Tooltip, Typography} from '@mui/material';
import {useFormik} from 'formik';
import TextFieldWithFnBox from "@/core/components/DataTable/filter/TextFieldWithFnBox/TextFieldWithFnBox";
import {useEffect, useState} from "react";
import useTableSetting from "@/lib/hooks/useTableSetting";
import BetweenNumberFilter from "@/core/components/DataTable/filter/BetweenNumberFilter";
import BetWeenDateFilter from "@/core/components/DataTable/filter/DatePicker/BetweenDateFilter";
import SelectBoxMultiple from "@/core/components/DataTable/filter/SelectBoxMultiple";
import SelectBox from "@/core/components/DataTable/filter/SelectBox";
import FilterAltIcon from '@mui/icons-material/FilterAlt';
import CloseIcon from '@mui/icons-material/Close';

function FilterColumn({columns}) {
    const [open, setOpen] = useState(false);
    const [selectedFilters, setSelectedFilters] = useState([]);
    const [userId, setUserId] = useState(2);
    const [pageName, setPageName] = useState('loan');
    const [tableName, setTableName] = useState('loan_table');
    const {settingStore, hideAction, filterAction, sortAction,} = useTableSetting();

    const DrawerHeader = styled('div')(({theme}) => ({
        display: 'flex',
        alignItems: 'center',
        padding: theme.spacing(0, 1),
        justifyContent: 'space-between',
    }));
    const toggleDrawer = (newOpen) => () => {
        setOpen(newOpen);
    };
    const handleDrawerClose = () => {
        setOpen(false);
    };
    useEffect(() => {
        const settingValue = settingStore?.[userId]?.[pageName]?.[tableName]?.['filters'] || [];
        setSelectedFilters(settingValue.length > 0 ? settingValue : []);
    }, [settingStore]);

    const handleSelectFilter = (fieldName, filterFn) => {
        const filterIndex = selectedFilters.findIndex(filter => filter.id === fieldName);

        if (filterIndex !== -1) {
            const updatedFilters = [...selectedFilters];
            updatedFilters[filterIndex].fn = filterFn;
            setSelectedFilters(updatedFilters);
        } else {
            const newFilter = {id: fieldName, fn: filterFn};
            const updatedFilters = [...selectedFilters, newFilter];
            setSelectedFilters(updatedFilters);
        }
    };

    const initialValues = columns.reduce((acc, column) => {
        if (column.enableColumnFilter) {
            const filter = settingStore?.[userId]?.[pageName]?.[tableName]?.['filters']?.find((filter) => filter.id === column.id);
            if (column.filterFn === 'betweenNum' || column.filterFn === 'betweenDate') {
                acc[column.id] = filter?.value || ["", ""];
            } else if (column.type === 'select2') {
                acc[column.id] = filter?.value || [];
            } else {
                acc[column.id] = filter?.value || '';
            }
        }
        return acc;
    }, {});

    const formik = useFormik({
        initialValues,
        onSubmit: (values) => {
            const updatedFilters = selectedFilters.map(filter => {
                const value = values[filter.id];
                if (value !== undefined) {
                    return {...filter, value};
                }
                return filter;
            });
            Object.entries(values).forEach(([fieldName, value]) => {
                const filterIndex = updatedFilters.findIndex(filter => filter.id === fieldName);
                if (filterIndex === -1 && value !== '' && value !== null && value !== undefined) {
                    const column = columns.find(col => col.id === fieldName);
                    updatedFilters.push({id: fieldName, value, fn: column.filterFn, datatype: column.datatype});
                }
            });

            const newArrayFilter = updatedFilters.filter((filter) => {
                const value = values[filter.id];

                return (
                    value !== '' &&
                    value !== null &&
                    value !== undefined &&
                    !(Array.isArray(value) && (value.length === 0 || (value.length === 2 && value.every((v) => v === ''))))
                );
            });

            setSelectedFilters(newArrayFilter);
            filterAction(userId, pageName, tableName, newArrayFilter, columns);
        }

    });

    return (
        <>
            <Tooltip title="فیلتر">
                <IconButton onClick={toggleDrawer(true)} aria-label="filter table">
                    <FilterAltIcon/>
                </IconButton>
            </Tooltip>
            <Drawer open={open} onClose={toggleDrawer(false)}
                    sx={{
                        "& .MuiDrawer-paper": {
                            padding: '16px',
                            overflowY: 'auto',
                            display: 'flex',
                            flexDirection: 'column',
                            justifyContent: 'space-between',
                            scrollbarWidth: 'thin',
                            width: 450,
                            "&::-webkit-scrollbar": {
                                width: '8px',
                            },
                            "&::-webkit-scrollbar-thumb": {
                                backgroundColor: '#ccc',
                                borderRadius: '4px',
                            },
                            "@media (max-width: 600px)": {
                                width: '100%'
                            },
                        }
                    }}
            >
                <DrawerHeader>
                    <Typography variant="h6" mb={2}>فیلتر</Typography>
                    <IconButton onClick={handleDrawerClose}>
                        <CloseIcon/>
                    </IconButton>
                </DrawerHeader>
                <Box sx={{display: 'flex', flexDirection: 'column'}}>
                    <FormControl fullWidth>
                        {columns.map((column, index) => (
                            column.enableColumnFilter &&
                            (column.filterFn === 'betweenDate' ?
                                    <BetWeenDateFilter
                                        key={index}
                                        id={column.id}
                                        formik={formik}
                                        onSelectFilter={(filterFn) => handleSelectFilter(column.id, filterFn)}
                                        defaultValue={(settingStore?.[userId]?.[pageName]?.[tableName]?.['filters'] || []).find(filter => filter.id === column.id)?.value || ''}
                                    />
                                    : column.filterFn === 'betweenNum' ?
                                        <BetweenNumberFilter
                                            key={index}
                                            id={column.id}
                                            formik={formik}
                                            onSelectFilter={(filterFn) => handleSelectFilter(column.id, filterFn)}
                                            defaultValue={(settingStore?.[userId]?.[pageName]?.[tableName]?.['filters'] || []).find(filter => filter.id === column.id)?.value || ["", ""]}
                                        />
                                        : column.type === 'select2' ?
                                            <SelectBoxMultiple
                                                key={index}
                                                id={column.id}
                                                formik={formik}
                                                onSelectFilter={(filterFn) => handleSelectFilter(column.id, filterFn)}
                                                defaultValue={(settingStore?.[userId]?.[pageName]?.[tableName]?.['filters'] || []).find(filter => filter.id === column.id)?.value || []}
                                            />
                                            : column.type === 'select' ?
                                                <SelectBox
                                                    key={index}
                                                    id={column.id}
                                                    formik={formik}
                                                    onSelectFilter={(filterFn) => handleSelectFilter(column.id, filterFn)}
                                                    defaultValue={(settingStore?.[userId]?.[pageName]?.[tableName]?.['filters'] || []).find(filter => filter.id === column.id)?.value || ''}
                                                />
                                                :
                                                <TextFieldWithFnBox
                                                    key={index}
                                                    id={column.id}
                                                    header={column.header}
                                                    formik={formik}
                                                    defaultFilter={(settingStore?.[userId]?.[pageName]?.[tableName]?.['filters'] || []).find(filter => filter.id === column.id)?.fn || column.filterFn}
                                                    columnFilterModeOptions={column.columnFilterModeOptions}
                                                    onSelectFilter={(filterFn) => handleSelectFilter(column.id, filterFn)}
                                                    defaultValue={formik.values[column.id] || (settingStore?.[userId]?.[pageName]?.[tableName]?.['filters'] || []).find(filter => filter.id === column.id)?.value || ''}
                                                />
                            )
                        ))}
                    </FormControl>
                </Box>
                <Box sx={{mt: 2}}>
                    <Divider/>
                    <Box sx={{display: 'flex', justifyContent: 'flex-end', alignItems: 'center'}}>
                        <Button variant="contained" size="medium" onClick={formik.handleSubmit}
                                sx={{mt: 1}}>ثبت</Button>
                    </Box>
                </Box>
            </Drawer>
        </>
    );
}

export default FilterColumn;


