import {useCallback, useState} from "@wordpress/element";
import {__, sprintf} from "@wordpress/i18n";
import ContentBodyInner from "../../../../containers/content/body-inner";
import Container from "../../../../containers/content/container";
import ExportCSV from "./export-csv";
import SectionHeader from "../../../../../../sections/section-header";
import Filters from "./filters";
import ContentFooterLayout from "../../../../containers/content/footer/_components/layout";
import Button from "../../../../../../button/_";
import {handleError} from "../../../../../../../helpers/notifications";
import {GetActionEntries} from "../../../../../../../rest/action-entires";
import ContentLoading from "../../../../containers/content/loading";
import Table from "./table";

export default function Entries({action, close, addNotification}) {
    const [loading, setLoading] = useState(0);
    const [isDataFetched, setIsDataFetched] = useState(false);
    const [entries, setEntries] = useState([]);
    const [pagination, setPagination] = useState({
        page: 1,
        perPage: LimbChatbot.screen_options?.lbaic_items_per_page || 10,
        total: 0,
    });
    const [order, setOrder] = useState({
        orderBy: 'created_at',
        order: 'desc',
    });
    const [filters, setFilters] = useState({});

    /**
     * Get entries
     *
     * @param {number} page Page
     * @param {number} perPage Per page
     * @param {object} params Params
     * @return {Promise<void>}
     */
    const getEntries = useCallback(async (page, perPage, params = {}) => {
        setLoading(prev => prev + 1);

        let items, total;
        const orderBy = params?.order_by || order.orderBy;
        const orderDir = params?.order || order.order;
        try {
            // More params
            const moreParams = {
                ...filters,
                ...params
            };
            // Remove empty strings, null, and undefined
            const cleanMoreParams = Object.fromEntries(
                Object.entries(moreParams).filter(([_, v]) => v !== '' && v != null)
            );

            const res = await GetActionEntries(action.id, {
                page: page,
                per_page: perPage,
                order_by: orderBy,
                order: orderDir,
                ...cleanMoreParams
            });

            items = res?.items || [];
            total = +res?.total || 0;
        } catch (e) {
            handleError(e, addNotification, {
                title: __("Failed to fetch action entries.", 'limb-chatbot'),
                description: e.message ? e.message : __("Something went wrong.", 'limb-chatbot')
            });
        }

        // Update entires state
        setEntries(items);
        setPagination(prevState => ({
            ...prevState,
            page: page,
            total: total,
        }));
        setOrder(prevState => ({
            ...prevState,
            order_by: orderBy,
            order: orderDir,
        }));

        setLoading(prev => prev - 1);
        setIsDataFetched(true);
    }, [action?.id, order.orderBy, order.order, filters]);

    const filterEntries = useCallback(async (filterParams) => {
        await getEntries(1, pagination.perPage, filterParams);
    }, [action?.id, pagination.perPage, filters]);

    return (
        <>
            <ContentBodyInner>
                {!isDataFetched && <ContentLoading/>}
                <Container className="lbaic-settings-a-entries">
                    <div className="lbaic-settings-a-entries-header">
                        <SectionHeader
                            title={__("Entries", 'limb-chatbot') + ': ' + (action?.name || 'request_voucher')}
                            description={sprintf(__("%d entries collected", 'limb-chatbot'), pagination.total)}
                        />
                        {/*<ExportCSV/>*/}
                    </div>
                    <Filters
                        filterEntries={filterEntries}
                        setFilters={setFilters}
                    />
                    <div className="lbaic-settings-divider-gap-end"/>
                    <Table
                        actionParameters={action?.parameters?.items || []}
                        entries={entries}
                        pagination={pagination}
                        order={order}
                        loading={loading > 0}
                        isDataFetched={isDataFetched}
                        _callback={getEntries}
                    />
                </Container>
            </ContentBodyInner>
            <ContentFooterLayout loading={loading > 0}>
                <Button
                    type="secondary"
                    label={__("Back", 'limb-chatbot')}
                    icon="arrow-left"
                    onClick={close}
                />
            </ContentFooterLayout>
        </>
    );
}