import {useEffect, useState} from "@wordpress/element";
import {__} from "@wordpress/i18n";
import Dropdown from "../../dropdown";
import {GetLeadsColumns} from "../../../../rest/leads";
import {handleError} from "../../../../helpers/notifications";
import AddLeadField from "../../../popups/leads/add-lead-field";

export default function LeadFieldMap({
                                         value,
                                         setValue,
                                         placeholder,
                                         disabled,
                                         notifications,
                                         ...props
                                     }) {
    const [leadColumns, setLeadColumns] = useState([]);
    const [leadColumnsLoading, setLeadColumnsLoading] = useState(true);
    const [showAddPopup, setShowAddPopup] = useState(false);
    const [pagination, setPagination] = useState({
        page: 1,
        perPage: 10,
        total: 0
    });

    /**
     * Fetch Leads table columns
     *
     * @param {object} params Query parameters
     * @param {boolean} reset Whether to reset the list (true) or append (false)
     * @return {Promise<void>}
     */
    const fetchLeadColumns = async (params = {}, reset = true) => {
        setLeadColumnsLoading(true);
        try {
            const res = await GetLeadsColumns(params);
            const items = Array.isArray(res?.items) ? res.items : [];
            const mappedItems = items.map((c) => ({
                label: c.label || '',
                value: c.id || ''
            }));

            if (reset) {
                setLeadColumns(mappedItems);
            } else {
                setLeadColumns(prev => [...prev, ...mappedItems]);
            }

            // Update pagination
            if (res) {
                setPagination({
                    page: res.page || pagination.page,
                    perPage: res.per_page || pagination.perPage,
                    total: res.total || 0
                });
            }
        } catch (e) {
            handleError(e, notifications?.set, {
                title: __("Could not load Leads columns.", 'limb-chatbot'),
                description: e?.message ? __(e.message, 'limb-chatbot') : __("Something went wrong.", 'limb-chatbot'),
            });
            if (reset) {
                setLeadColumns([]);
            }
        } finally {
            setLeadColumnsLoading(false);
        }
    };

    /**
     * Load more columns
     *
     * @param {object} params Query parameters with page and perPage
     * @return {Promise<void>}
     */
    const loadMoreColumns = async (params) => {
        await fetchLeadColumns(params, false);
    };

    useEffect(() => {
        fetchLeadColumns({
            page: 1,
            per_page: 10
        }, true);
    }, []);

    /**
     * Handle new lead field added
     *
     * @param {object} newField New field from API {id, field_key, label, data_type}
     */
    const handleNewFieldAdded = (newField) => {
        const newOption = {
            label: newField.label || '',
            value: newField.id || ''
        };
        setLeadColumns(prev => [...prev, newOption]);
        // Auto-select the new field
        setValue(newField.id);
    };

    /**
     * Handle add new click
     */
    const handleAddNew = () => {
        setShowAddPopup(true);
    };

    return (
        <>
            <Dropdown
                value={value ?? ''}
                setValue={setValue}
                options={[
                    {
                        label: __("Select", 'limb-chatbot'),
                        value: ''
                    },
                    ...leadColumns
                ]}
                placeholder={placeholder || __("Map to Leads column", 'limb-chatbot')}
                disabled={disabled || leadColumnsLoading}
                addNew={handleAddNew}
                loadMore={loadMoreColumns}
                pagination={{
                    get: pagination,
                    set: setPagination,
                }}
                {...props}
            />
            {showAddPopup && (
                <AddLeadField
                    close={() => setShowAddPopup(false)}
                    onSuccess={handleNewFieldAdded}
                    notifications={notifications}
                />
            )}
        </>
    );
}
