import {__, sprintf} from "@wordpress/i18n";
import ContentFooterLayout from "../../../../containers/content/footer/_components/layout";
import Button from "../../../../../../button/_";
import ButtonPlayPauseCancel from "../../../../../../button/play-pause-cancel";

export default function Footer({
                                   add,
                                   save,
                                   resume,
                                   pause,
                                   cancel,
                                   cancelForm,
                                   deleteSelected,
                                   syncSelected,
                                   addingEditing,
                                   processState,
                                   generatingProgress,
                                   syncingProgress,
                                   deletingProgress,
                                   totalCount,
                                   loading,
                                   saving,
                                   syncing,
                                   deleting,
                                   pausing,
                                   canceling,
                                   preparing,
                                   selectedItems,
                                   isAllPageSelected,
                                   onToggleSelectAll,
                                   currentPageItemsCount,
                                   showFilter,
                                   toggleFilter,
                                   hasActiveFilters,
                                   applyFilters,
                                   filteringLoading,
                                   giFormRef,
                                   onLoadSitemap
                               }) {
    // Determine progress for main process (generating)
    let mainProgress;
    if (processState?.type === 'dataset_generating') {
        mainProgress = generatingProgress;
    } else {
        mainProgress = false;
    }

    // Has selected (excluding "all" state for this check)
    const hasSelected = selectedItems?.length > 0 && !(selectedItems.length === 1 && selectedItems[0] === "all");
    // Check if dataset operations are running (not saving/generating)
    const datasetOperationsRunning = Boolean(syncing.length > 0 || deleting.length > 0);

    // Doing
    const doing = Boolean(loading || saving || pausing || canceling || preparing || datasetOperationsRunning);

    // PlayPause disabled - disable play when dataset operations running, but NEVER disable pause when saving
    const playPauseDisabled = Boolean(loading || pausing || canceling || preparing || datasetOperationsRunning || (!saving && datasetOperationsRunning));

    // Stop button disabled - allow when process is active OR paused, but not when already canceling or loading
    const stopDisabled = Boolean(
        loading
        || canceling
        || preparing
        ||
        !(
            processState?.type === 'dataset_generating'
            && (processState?.status === 'start' || processState?.status === 'pause')
        )
    );

    // Delete disabled - disabled if there's an active process and it's not dataset_delete
    const deleteDisabled = Boolean(
        loading ||
        preparing ||
        (processState?.type && processState?.type !== 'dataset_delete')
    );

    // Sync disabled - disabled if there's an active process and it's not dataset_sync
    const syncDisabled = Boolean(
        loading ||
        preparing ||
        (processState?.type && processState?.type !== 'dataset_sync')
    );

    // Cancel disabled for Delete - allow when delete process is active OR paused
    const deleteCancelDisabled = Boolean(
        loading ||
        canceling ||
        preparing ||
        !(
            processState?.type === 'dataset_delete'
            && (processState?.status === 'start' || processState?.status === 'pause')
        )
    );

    // Cancel disabled for Sync - allow when sync process is active OR paused
    const syncCancelDisabled = Boolean(
        loading ||
        canceling ||
        preparing ||
        !(
            processState?.type === 'dataset_sync'
            && (processState?.status === 'start' || processState?.status === 'pause')
        )
    );

    const showMainProcessButtons = addingEditing || processState?.type === 'dataset_generating';

    // Check if source is sitemap (but not when generating job is running)
    const sourceType = giFormRef?.current?.getSourceType?.();
    const isSitemapSource = sourceType === 'sitemap' && processState?.type !== 'dataset_generating';

    // Show button when all page items are selected OR when "all" is selected
    // But only if there are more items beyond the current page
    const isAllState = selectedItems?.length === 1 && selectedItems[0] === "all";
    const hasMoreItems = totalCount > currentPageItemsCount;
    const showSelectAllButton = (isAllPageSelected || isAllState) && hasMoreItems && totalCount > 0 && !showMainProcessButtons;

    // Show Cancel button when form is open, but NOT during job creation, processing, or when paused
    const showCancelButton = addingEditing &&
        !preparing &&
        !(processState?.type === 'dataset_generating' && processState?.status === 'start') &&
        !(processState?.type === 'dataset_generating' && processState?.status === 'pause');

    return <ContentFooterLayout loading={doing}>
        {!showMainProcessButtons ?
            ((totalCount > 0 || hasActiveFilters) && (
                <>
                    {!showFilter && (
                        <Button
                            type="primary"
                            label={__("Add source", 'limb-chatbot')}
                            onClick={add}
                            disabled={!!processState?.type || preparing}
                            className="lbaic-settings-content-footer-actions-in"
                        />
                    )}
                    {showFilter && (
                        <>
                            <Button
                                type="primary"
                                label={__("Apply", 'limb-chatbot')}
                                onClick={applyFilters}
                                loading={filteringLoading}
                                disabled={!!processState?.type || preparing || filteringLoading}
                                className="lbaic-settings-content-footer-actions-in"
                            />
                            <Button
                                type="secondary"
                                label={__("Cancel", 'limb-chatbot')}
                                onClick={toggleFilter}
                                disabled={!!processState?.type || preparing}
                                className="lbaic-settings-content-footer-actions-in lbaic-settings-content-footer-actions-end"
                            />
                        </>
                    )}
                    {!showFilter && (
                        <Button
                            type="secondary"
                            label={__("Filter", 'limb-chatbot')}
                            icon="filter"
                            onClick={toggleFilter}
                            disabled={!!processState?.type || preparing}
                            className="lbaic-settings-content-footer-actions-in lbaic-settings-content-footer-actions-end"
                        />
                    )}
                </>
            )) : (
                <>
                    {isSitemapSource ? (
                        <Button
                            type="primary"
                            label={__("Import sitemap", 'limb-chatbot')}
                            icon="download"
                            onClick={onLoadSitemap}
                            disabled={loading || preparing}
                            className={`lbaic-settings-content-footer-actions-in${!showCancelButton ? ' lbaic-settings-content-footer-actions-end' : ''}`}
                        />
                    ) : (
                        <ButtonPlayPauseCancel
                            label={__("Learn", 'limb-chatbot')}
                            icon="run"
                            type="primary"
                            playing={processState?.status === 'start' && processState?.type === 'dataset_generating'}
                            paused={processState?.status === 'pause' && processState?.type === 'dataset_generating'}
                            progress={mainProgress}
                            play={processState?.status === 'pause' ? resume : save}
                            pause={pause}
                            cancel={cancel}
                            playPauseDisabled={playPauseDisabled}
                            cancelDisabled={stopDisabled}
                            canceling={canceling}
                            isEndOfActions={!showCancelButton}
                        />
                    )}
                    {showCancelButton && (
                        <Button
                            type="secondary"
                            label={__("Cancel", 'limb-chatbot')}
                            onClick={cancelForm}
                            className="lbaic-settings-content-footer-actions-in lbaic-settings-content-footer-actions-end"
                        />
                    )}
                </>
            )}
        {(hasSelected || (selectedItems?.length === 1 && selectedItems[0] === "all")) && (
            <>
                {showSelectAllButton && (
                    <Button
                        type="secondary"
                        label={isAllState ? __("Clear selection", 'limb-chatbot') : sprintf(__("Select all %d", 'limb-chatbot'), totalCount)}
                        onClick={onToggleSelectAll}
                        disabled={!!processState?.type || preparing}
                        className="lbaic-settings-content-footer-actions-in"
                    />
                )}
                <ButtonPlayPauseCancel
                    label={__("Delete", 'limb-chatbot')}
                    icon="delete"
                    type="danger"
                    playing={processState?.status === 'start' && processState?.type === 'dataset_delete'}
                    paused={processState?.status === 'pause' && processState?.type === 'dataset_delete'}
                    progress={deletingProgress}
                    play={deleteSelected}
                    pause={pause}
                    cancel={cancel}
                    playPauseDisabled={deleteDisabled}
                    cancelDisabled={deleteCancelDisabled}
                    canceling={canceling}
                />
                <ButtonPlayPauseCancel
                    label={__("Update", 'limb-chatbot')}
                    icon="sync"
                    type="secondary"
                    playing={processState?.status === 'start' && processState?.type === 'dataset_sync'}
                    paused={processState?.status === 'pause' && processState?.type === 'dataset_sync'}
                    progress={syncingProgress}
                    play={syncSelected}
                    pause={pause}
                    cancel={cancel}
                    playPauseDisabled={syncDisabled}
                    cancelDisabled={syncCancelDisabled}
                    canceling={canceling}
                    className="lbaic-settings-a-ei-footer-actions-in"
                />
            </>
        )}
    </ContentFooterLayout>
}
