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

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({
                                    filterLeads,
                                    setFilters,
                                    setSelectedLeads,
                                    setSelectAll,
                                    setIsAllSelected,
                                    allColumns,
                                    onConfigureColumnsChange
                                }) {
    const [searchValue, setSearchValue] = useState('');
    const [dateValue, setDateValue] = useState(null);
    const [statusValue, setStatusValue] = useState(null);
    const [sourceValue, setSourceValue] = useState(null);
    const searchDebounceRef = useRef(null);

    const clearSelections = () => {
        setSelectedLeads([]);
        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 = {
                value_search: value || undefined
            };

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

            clearSelections();
            await filterLeads(reqData);
        }, 400);
    }, [filterLeads, setFilters, setSelectedLeads, 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 filterLeads(reqData);
    }, [filterLeads, setFilters, setSelectedLeads, setSelectAll, setIsAllSelected]);

    /**
     * Handle status filter change
     */
    const handleStatusChange = useCallback(async (value) => {
        setStatusValue(value);

        const reqData = {
            status: value || undefined
        };

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

        clearSelections();
        await filterLeads(reqData);
    }, [filterLeads, setFilters, setSelectedLeads, setSelectAll, setIsAllSelected]);

    /**
     * Handle source filter change
     */
    const handleSourceChange = useCallback(async (value) => {
        setSourceValue(value);

        const reqData = {
            source: value || undefined
        };

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

        clearSelections();
        await filterLeads(reqData);
    }, [filterLeads, setFilters, setSelectedLeads, 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 leads", '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>

            {/* Filters Bar */}
            {/*<div className="lbaic-settings-leads-filters-bar">
                <div className="lbaic-settings-column">
                    <div className="lbaic-settings-column-in">
                         Status Filter
                        <Dropdown
                            value={statusValue}
                            setValue={handleStatusChange}
                            options={statusFilterOptions}
                            className="lbaic-settings-leads-filters-bar-dropdown"
                        />
                    </div>
                    <div className="lbaic-settings-column-in">
                         Source Filter
                        <Dropdown
                            value={sourceValue}
                            setValue={handleSourceChange}
                            options={sourceFilterOptions}
                            className="lbaic-settings-leads-filters-bar-dropdown"
                        />
                    </div>
                </div>
                <div className="lbaic-settings-leads-filters-bar-in">

                </div>
            </div>*/}
        </>
    );
}
