import {useCallback, useEffect, useState} from "@wordpress/element";
import {__, sprintf} from "@wordpress/i18n";
import ContentBodyInner from "../../../containers/content/body-inner";
import ContentLoading from "../../../containers/content/loading";
import Container from "../../../containers/content/container";
import Table from "../leads/table";
import Button from "../../../../../button/_";
import ContentFooterLayout from "../../../containers/content/footer/_components/layout";
import {handleError} from "../../../../../../helpers/notifications";
import {GetChatbotUsers} from "../../../../../../rest/chatbot-users";
import Filters from "./filters";
import {getVisibleColumns} from "./_components/configure-columns-button";

const COLUMNS = [
    {
        id: 'ip',
        label: __("IP", 'limb-chatbot'),
    },
    {
        id: 'geolocation',
        label: __("Location", 'limb-chatbot'),
    },
    {
        id: 'device_info',
        label: __("Device", 'limb-chatbot'),
    },
    {
        id: 'browser',
        label: __("Browser", 'limb-chatbot'),
    },
    {
        id: 'wp_user',
        label: __("WP User", 'limb-chatbot'),
    },
    {
        id: 'created_at',
        label: __("Created at", 'limb-chatbot'),
    }
];

export default function VisitorsVisitors({notifications}) {
    const [loading, setLoading] = useState(0);
    const [isDataFetched, setIsDataFetched] = useState(false);
    const [visitorsData, setVisitorsData] = useState([]);
    const [pagination, setPagination] = useState({
        page: 1,
        perPage: LimbChatbot.screen_options?.lbaic_items_per_page || 10,
        total: 0,
    });
    const [filters, setFilters] = useState({});
    const [selectedVisitors, setSelectedVisitors] = useState([]);
    const [selectAll, setSelectAll] = useState(false);
    const [isAllSelected, setIsAllSelected] = useState(false);
    const [selectedVisitor, setSelectedVisitor] = useState(null);
    const [isDrawerOpen, setIsDrawerOpen] = useState(false);
    const [visibleColumns, setVisibleColumns] = useState(getVisibleColumns(COLUMNS));

    const fetchVisitors = useCallback(async (page, perPage, params = {}) => {
        setLoading(prev => prev + 1);

        let items, total;
        try {
            // Merge filters with params
            const moreParams = {
                ...filters,
                include: visibleColumns,
                ...params
            };

            // Remove empty strings, null, and undefined
            const cleanParams = Object.fromEntries(
                Object.entries(moreParams).filter(([_, v]) => v !== '' && v != null)
            );

            // Add search fields query param if search is present
            if ('search' in cleanParams) {
                cleanParams.search_fields = ['ip'];
            }

            const res = await GetChatbotUsers({
                page: page,
                per_page: perPage,
                orderby: 'created_at',
                order: 'desc',
                ...cleanParams
            });

            items = res?.items || [];
            total = res?.total || 0;
        } catch (e) {
            handleError(e, notifications.set, {
                title: __("Failed to fetch visitors.", 'limb-chatbot'),
                description: e.message ? __(e.message, 'limb-chatbot') : __("Please check and try again.", 'limb-chatbot'),
            });
            items = [];
            total = 0;
        }

        setVisitorsData(items);
        setPagination(prevState => ({
            ...prevState,
            page: page,
            total: total,
        }));

        setLoading(prev => prev - 1);
        setIsDataFetched(true);
    }, [filters, visibleColumns, notifications.set]);

    useEffect(() => {
        fetchVisitors(1, pagination.perPage);
    }, []);

    const filterVisitors = useCallback(async (filterParams) => {
        await fetchVisitors(1, pagination.perPage, filterParams);
    }, [fetchVisitors, pagination.perPage]);

    const handleVisitorSelect = (visitorId) => {
        setSelectedVisitors(prev => {
            const newSelected = prev.indexOf(visitorId) === -1
                ? [...prev, visitorId]
                : prev.filter(item => item !== visitorId);

            // Check if all current page items are selected
            const currentPageIds = visitorsData.map(visitor => visitor.id);
            const allPageSelected = currentPageIds.length > 0 &&
                currentPageIds.every(id => newSelected.includes(id));
            setSelectAll(allPageSelected);

            return newSelected;
        });
        setIsAllSelected(false);
    };

    const handleSelectAll = () => {
        if (selectAll) {
            setSelectedVisitors([]);
            setSelectAll(false);
            setIsAllSelected(false);
        } else {
            const allIds = visitorsData.map(visitor => visitor.id);
            setSelectedVisitors(allIds);
            setSelectAll(true);
            setIsAllSelected(false);
        }
    };

    const handleToggleSelectAll = () => {
        if (isAllSelected) {
            // Clear all selection
            setSelectedVisitors([]);
            setSelectAll(false);
            setIsAllSelected(false);
        } else {
            // Select all items (set a flag to select all)
            setIsAllSelected(true);
            setSelectAll(true);
        }
    };

    const handleRowClick = (e, visitorId) => {
        if (e.target.closest('.lbaic-settings-checkbox')) {
            return;
        }
        const visitorData = visitorsData.find(l => l.id === visitorId);
        if (visitorData) {
            setSelectedVisitor(visitorData);
            setIsDrawerOpen(true);
        }
    };

    const handleCloseDrawer = () => {
        setIsDrawerOpen(false);
        setSelectedVisitor(null);
    };

    const handleConfigureColumnsChange = (columns) => {
        setVisibleColumns(columns);
        filterVisitors({
            include: columns,
        });
    };

    return (
        <>
            <ContentBodyInner>
                {!isDataFetched && <ContentLoading/>}
                <Container className="lbaic-settings-visitors">
                    <Filters
                        allColumns={COLUMNS}
                        filterVisitors={filterVisitors}
                        setFilters={setFilters}
                        setSelectedVisitors={setSelectedVisitors}
                        setSelectAll={setSelectAll}
                        setIsAllSelected={setIsAllSelected}
                        onConfigureColumnsChange={handleConfigureColumnsChange}
                    />

                    <Table
                        selectedRows={selectedVisitors}
                        selectAll={selectAll}
                        onVisitorSelect={handleVisitorSelect}
                        onSelectAll={handleSelectAll}
                        onRowClick={handleRowClick}
                        allColumns={COLUMNS}
                        visibleColumns={visibleColumns}
                        tableData={visitorsData}
                        pagination={pagination}
                        loading={loading > 0}
                        isDataFetched={isDataFetched}
                        _callback={fetchVisitors}
                        emptyLabel={__("No visitors found.", 'limb-chatbot')}
                        paginationProps={{
                            totalItemsLabel: __("visitors", 'limb-chatbot'),
                        }}
                    />
                </Container>
            </ContentBodyInner>
            <ContentFooterLayout
                loading={loading > 0}
            >
                {(selectedVisitors.length > 0 || isAllSelected) && (
                    <>
                        {/* Show the "Select all X" button when all current page items are selected AND there are more items */}
                        {selectAll && !isAllSelected && pagination.total > visitorsData.length && (
                            <Button
                                type="secondary"
                                label={sprintf(__("Select all %d", 'limb-chatbot'), pagination.total)}
                                onClick={handleToggleSelectAll}
                                disabled={loading > 0}
                                className="lbaic-settings-content-footer-actions-in"
                            />
                        )}
                        {/* Show "Clear selection" when all items are selected */}
                        {isAllSelected && (
                            <Button
                                type="secondary"
                                label={__("Clear selection", 'limb-chatbot')}
                                onClick={handleToggleSelectAll}
                                disabled={loading > 0}
                                className="lbaic-settings-content-footer-actions-in"
                            />
                        )}
                        {/* Export button */}
                        <Button
                            type="secondary"
                            label={__("Export", 'limb-chatbot')}
                            icon="download"
                            onClick={() => {
                            }}
                            disabled={loading > 0}
                            className="lbaic-settings-content-footer-actions-in lbaic-settings-content-footer-actions-end"
                        />
                    </>
                )}
            </ContentFooterLayout>
        </>
    );
}