import {useCallback, useEffect, useRef, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import Button from "../../../../../../../button/_";
import Input from "../../../../../../../fields/input";
import {handleError} from "../../../../../../../../helpers/notifications";

/**
 * Get today's seconds
 *
 * @return {number}
 */
const getTodaySeconds = () => {
    const now = new Date();
    return now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds();
}

const FILTER_TIMES = [
    {
        label: __("All time", 'limb-chatbot'),
        value: null,
    },
    {
        label: __('Today', 'limb-chatbot'),
        value: 0,
    },
    {
        label: __("7 days", 'limb-chatbot'),
        value: 3600 * 24 * 6,
    },
    {
        label: __("30 days", 'limb-chatbot'),
        value: 3600 * 24 * 29,
    }
];

/**
 * Get starting_from 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);
        date.setHours(0, 0, 0, 0);

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

/**
 * Search fields
 *
 * @type {string[]}
 */
const SEARCH_FIELDS = ['action_data'];

export default function Filters({
                                    filterEntries,
                                    setFilters
                                }) {
    const [loading, setLoading] = useState(0);
    const [searchValue, setSearchValue] = useState('');
    const [selectedTimeIndex, setSelectedTimeIndex] = useState(2);
    const filterDebounceRef = useRef(null);

    useEffect(() => {
        handlePeriodUpdate(selectedTimeIndex);
    }, [selectedTimeIndex]);

    /**
     * Handle search value update
     *
     * @param {string} value Value
     */
    const handleSearchValueUpdate = useCallback((newValue) => {
        setSearchValue(newValue);

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

        filterDebounceRef.current = setTimeout(async () => {
            setLoading(prev => prev + 1);
            // Search
            const value = newValue.trim();
            // Request data
            const reqData = {
                search: value,
                search_fields: value ? SEARCH_FIELDS : null
            };
            // Update filters state
            setFilters(prevState => {
                const {search, search_fields, ...rest} = prevState;

                if (value) {
                    return {
                        ...rest,
                        ...reqData
                    }
                } else {
                    return rest;
                }
            });
            // Fetch entries
            await filterEntries(reqData);
            setLoading(prev => prev - 1);
        }, 400);
    }, [filterEntries, setFilters]);

    /**
     * Handle period update
     *
     * @param {number} index Index
     */
    const handlePeriodUpdate = useCallback(async (index) => {
        setSelectedTimeIndex(index);

        setLoading(prev => prev + 1);
        const startingFrom = getStartAt(FILTER_TIMES[index].value);
        // Request data
        const reqData = {
            starting_from: startingFrom
        };
        // Update filters state
        setFilters(prevState => {
            const {starting_from, ...rest} = prevState;

            if (startingFrom) {
                return {
                    ...rest,
                    ...reqData
                }

            } else {
                return rest;
            }
        });
        // Fetch entries
        await filterEntries(reqData);
        setLoading(prev => prev - 1);
    }, [filterEntries, setFilters]);

    return (
        <div className="lbaic-settings-a-entries-filter">
            <div className="lbaic-settings-a-entries-filter-in">
                <div className="lbaic-settings-a-entries-filter-search">
                    <Input
                        value={searchValue}
                        setValue={handleSearchValueUpdate}
                        staticPlaceholder={__("Search entries", 'limb-chatbot')}
                    >
                        <svg
                            className="lbaic-settings-a-entries-filter-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-a-entries-filter-periods">
                    {FILTER_TIMES.map((item, i) => {
                        const isSelected = selectedTimeIndex === i;

                        return (
                            <Button
                                key={i}
                                type={isSelected ? "primary" : "secondary"}
                                label={item.label}
                                onClick={() => handlePeriodUpdate(i)}
                                disabled={loading > 0}
                            />
                        )
                    })}
                </div>
            </div>
        </div>
    );
}