"use client"
import {
    Button,
    Dialog, DialogActions,
    DialogContent,
    DialogTitle,
    FormControl
} from '@mui/material';
import {useFormik} from 'formik';
import TextFieldWithFnBox from "@/components/TextFieldWithFnBox";
import {useEffect, useState} from "react";

function FilterColumn({ onSubmit , column  }) {
    const [selectedFilters, setSelectedFilters] = useState([]);

    useEffect(() => {
        const initialFilters = column
            .filter(col => col.ColumnFiterStatus)
            .map(col => ({ id: col.field, fn: col.filterFn }));
        setSelectedFilters(initialFilters);
    }, [column]);

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

    const formik = useFormik({
        initialValues: column.reduce((acc, column) => {
            if (column.ColumnFiterStatus) {
                acc[column.field] = '';
            }
            return acc;
        }, {}),
        onSubmit: (values) => {
            // const selectedFilters = [
            //     { "id": "name", "value": values.name1, "fn": values.cityFn, "datatype": values.nameDatatype },
            //     { "id": "navgan_id", "value": values.name2, "fn": values.nameFn, "datatype": values.nameDatatype }
            // ];

            const user_id = 456;
            const page_name = 'loan';
            const table_name = "amir_table";

            let prevLocalStorage = JSON.parse(localStorage.getItem("_setting-app")) || {};

            const existingFilters = prevLocalStorage[user_id]?.[page_name]?.[table_name]?.filters || [];

            const updatedFilters = selectedFilters.reduce((acc, filter) => {
                const currentValue = values[filter.id];
                const prevValue = formik.initialValues[filter.id];
                console.log(acc, filter)
                // Check if the current value is empty and the previous value was not empty
                if ((currentValue === '' || currentValue === undefined || currentValue === null) && prevValue !== '' && prevValue !== undefined && prevValue !== null) {
                    // Remove filter data from localStorage
                    const filterIndex = existingFilters.findIndex(f => f.id === filter.id);
                    console.log({filterIndex})
                    if (filterIndex !== -1) {
                        existingFilters.splice(filterIndex, 1);
                    }
                } else {
                    acc.push({
                        ...filter,
                        value: currentValue,
                        datatype: column.find(col => col.field === filter.id).datatype
                    });
                }

                return acc;
            }, []);


            updatedFilters.forEach(newFilter => {
                const existingFilterIndex = existingFilters.findIndex(filter => filter.id === newFilter.id);
                existingFilterIndex !== -1 ? existingFilters[existingFilterIndex] = newFilter : existingFilters.push(newFilter);
            });

            prevLocalStorage[user_id] = prevLocalStorage[user_id] || {};
            prevLocalStorage[user_id][page_name] = prevLocalStorage[user_id][page_name] || {};
            prevLocalStorage[user_id][page_name][table_name] = { hides: {}, filters: existingFilters };

            localStorage.setItem('_setting-app', JSON.stringify(prevLocalStorage));

            onSubmit(updatedFilters);
        }
    });


    return (
        <Dialog open={true}>
            <DialogTitle>Select Filters</DialogTitle>
            <DialogContent>
                <FormControl fullWidth>
                    {column.map((column, index) => (
                        column.ColumnFiterStatus &&
                        <TextFieldWithFnBox
                            key={index}
                            formik={formik}
                            fieldName={column.field}
                            label={column.label}
                            defaultFilter={column.defaultFilter}
                            columnFilterModeOptions={column.columnFilterModeOptions}
                            onSelectFilter={(filterFn) => handleSelectFilter(column.field, filterFn)}
                        />
                    ))}
                </FormControl>
            </DialogContent>
            <DialogActions>
                <Button onClick={formik.handleSubmit}>Submit</Button>
            </DialogActions>
        </Dialog>
    );
}

export default FilterColumn;


