import {useCallback, useRef, useState} from "@wordpress/element";
import {__, sprintf} from "@wordpress/i18n";
import Input from "../../../../../../fields/input";
import Dropdown from "../../../../../../fields/dropdown";
import {handleError} from "../../../../../../../helpers/notifications";
import ConfigureColumnsButton from "../_components/configure-columns-button";

const DATE_FILTER_OPTIONS = [
    {
        label: __("All Time", 'limb-chatbot'),
        value: null
    },
    {
        label: __("Today", 'limb-chatbot'),
        value: 0
    },
    {
        label: sprintf(__("Last %d days", 'limb-chatbot'), 7),
        value: 3600 * 24 * 7
    },
    {
        label: sprintf(__("Last %d days", 'limb-chatbot'), 30),
        value: 3600 * 24 * 30
    },
    {
        label: sprintf(__("Last %d days", 'limb-chatbot'), 90),
        value: 3600 * 24 * 90
    }
];

/**
 * Get start_date param
 *
 * @param {null|number} period Period in seconds
 * @return {string|null}
 */
const getStartAt = (period) => {
    if (period === null) {
        return null;
    }

    try {
        const date = new Date(Date.now() - period * 1000);

        // Today
        if (!period) {
            date.setHours(0, 0, 0, 0);
        }

        return date.toISOString().slice(0, 19).replace('T', ' ');
    } catch (e) {
        handleError(e);
        return null;
    }
}

export default function Filters({
                                    allColumns,
                                    filterVisitors,
                                    setFilters,
                                    setSelectedVisitors,
                                    setSelectAll,
                                    setIsAllSelected,
                                    onConfigureColumnsChange
                                }) {
    const [searchValue, setSearchValue] = useState('');
    const [dateValue, setDateValue] = useState(null);
    const searchDebounceRef = useRef(null);

    const clearSelections = () => {
        setSelectedVisitors([]);
        setSelectAll(false);
        setIsAllSelected(false);
    };

    /**
     * Handle search value update
     */
    const handleSearchChange = useCallback((newValue) => {
        setSearchValue(newValue);

        if (searchDebounceRef.current) {
            clearTimeout(searchDebounceRef.current);
        }

        searchDebounceRef.current = setTimeout(async () => {
            const value = newValue.trim();
            const reqData = {
                search: value || undefined
            };

            // Update filters state
            setFilters(prevState => {
                const {search, ...rest} = prevState;
                if (value) {
                    return {...rest, ...reqData};
                }
                return rest;
            });

            clearSelections();
            await filterVisitors(reqData);
        }, 400);
    }, [filterVisitors, setFilters, setSelectedVisitors, setSelectAll, setIsAllSelected]);

    /**
     * Handle date filter change
     */
    const handleDateChange = useCallback(async (value) => {
        setDateValue(value);

        const startAt = getStartAt(value);

        const reqData = {
            start_date: startAt
        };

        // Update filters state
        setFilters(prevState => {
            const {start_date, ...rest} = prevState;
            if (startAt) {
                return {...rest, ...reqData};
            }
            return rest;
        });

        clearSelections();
        await filterVisitors(reqData);
    }, [filterVisitors, setFilters, setSelectedVisitors, setSelectAll, setIsAllSelected]);

    return (
        <>
            <div className="lbaic-settings-filters-bar">
                <div className="lbaic-settings-column lbaic-settings-column-w-100">
                    <div className="lbaic-settings-column-in">
                        {/* Search */}
                        <Input
                            value={searchValue}
                            setValue={handleSearchChange}
                            staticPlaceholder={__("Search visitors by IP", 'limb-chatbot')}
                            className="lbaic-settings-leads-filters-bar-search"
                        >
                            <svg
                                className="lbaic-settings-leads-filters-bar-search-icon"
                                xmlns="http://www.w3.org/2000/svg"
                                fill="none"
                                viewBox="0 0 24 24"
                            >
                                <use href="#lbaic-settings-search"/>
                            </svg>
                        </Input>
                    </div>
                    <div className="lbaic-settings-column-in">
                        {/* Date Filter */}
                        <Dropdown
                            value={dateValue}
                            setValue={handleDateChange}
                            options={DATE_FILTER_OPTIONS}
                            className="lbaic-settings-leads-filters-bar-dropdown"
                        />
                    </div>
                </div>
                <div className="lbaic-settings-filters-bar-in">
                    {/* Configure columns */}
                    <ConfigureColumnsButton
                        allColumns={allColumns}
                        onColumnsChange={onConfigureColumnsChange}
                    />
                </div>
            </div>
        </>
    );
}