import { useState, useRef, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
    ToggleControl,
    TextControl,
    Button
} from '@wordpress/components';
import {
    edit,
    check,
    close,
    menu
} from '@wordpress/icons';
import {
    getAvailableTabs,
    getVisibleTabs,
    getTabLabel,
    getAllTabsInOrder,
    reorderTabs
} from '../utils/tab-utils';

/**
 * TabManager Component
 * 
 * A reusable component for managing tabs with drag-and-drop reordering,
 * inline editing, and enable/disable functionality.
 * 
 * @param {Object} props - Component props
 * @param {Object} props.tabs - Available tabs object { tabId: label }
 * @param {Array} props.enabledTabs - Array of enabled tab IDs
 * @param {Array} props.tabOrder - Array defining tab order
 * @param {Object} props.customLabels - Object for custom labels
 * @param {Function} props.onChange - Callback function called with updates
 * @param {string} props.placeholder - Optional placeholder text
 * @param {boolean} props.sortable - Enable drag & drop reordering (default: true)
 * @param {boolean} props.editable - Enable inline editing (default: true)
 * @param {string} props.className - Additional CSS classes
 */
const TabManager = ({ 
    tabs = {},
    enabledTabs = [], 
    tabOrder = [], 
    customLabels = {}, 
    onChange,
    placeholder = __('No tabs available', 'wpuf-pro'),
    sortable = true,
    editable = true,
    className = ''
}) => {
    const [editingTab, setEditingTab] = useState(null);
    const [editValue, setEditValue] = useState('');
    const [dragIndex, setDragIndex] = useState(null);
    const containerRef = useRef(null);

    // Get available tabs (merge with provided tabs)
    const availableTabs = getAvailableTabs(tabs);
    
    // Get all tabs in order
    const allTabsInOrder = getAllTabsInOrder(tabOrder, availableTabs);
    
    // Get visible tabs
    const visibleTabs = getVisibleTabs(enabledTabs, tabOrder, availableTabs);

    // Close dropdown on outside click
    useEffect(() => {
        const handleClick = (e) => {
            if (containerRef.current && !containerRef.current.contains(e.target)) {
                setEditingTab(null);
                setEditValue('');
            }
        };
        document.addEventListener('mousedown', handleClick);
        return () => document.removeEventListener('mousedown', handleClick);
    }, []);

    // Handle tab toggle (enable/disable)
    const handleTabToggle = (tabId, enabled) => {
        if (enabled) {
            // Add tab to enabledTabs if not already present
            if (!enabledTabs.includes(tabId)) {
                const next = [...enabledTabs, tabId];
                onChange({ enabledTabs: next });
            }
        } else {
            // Remove tab from enabledTabs only
            const next = enabledTabs.filter(id => id !== tabId);
            onChange({ enabledTabs: next });
        }
    };

    // Handle tab rename
    const handleTabRename = (tabId) => {
        setEditingTab(tabId);
        const label = getTabLabel(tabId, customLabels, availableTabs);
        setEditValue(label);
    };

    // Save tab rename
    const saveTabRename = () => {
        if (editingTab && editValue.trim()) {
            const newCustomLabels = { ...customLabels };
            newCustomLabels[editingTab] = editValue.trim();
            onChange({ customLabels: newCustomLabels });
        }
        setEditingTab(null);
        setEditValue('');
    };

    // Cancel tab rename
    const cancelTabRename = () => {
        setEditingTab(null);
        setEditValue('');
    };

    // Handle tab reorder
    const handleTabReorder = (fromIndex, toIndex) => {
        if (!sortable || fromIndex === toIndex) return;
        
        const newOrder = reorderTabs(tabOrder, fromIndex, toIndex, availableTabs);
        onChange({ tabOrder: newOrder });
    };

    // Drag and drop handlers
    const handleDragStart = (e, index) => {
        if (!sortable) return;
        
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/html', e.currentTarget.outerHTML);
        e.currentTarget.classList.add('wpuf-dragging');
        setDragIndex(index);
    };

    const handleDragOver = (e, index) => {
        if (!sortable || dragIndex === null || dragIndex === index) return;
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';
    };

    const handleDrop = (e, index) => {
        if (!sortable) return;
        
        e.preventDefault();
        if (dragIndex !== null && dragIndex !== index) {
            handleTabReorder(dragIndex, index);
        }
    };

    const handleDragEnd = (e) => {
        if (!sortable) return;
        
        e.currentTarget.classList.remove('wpuf-dragging');
        setDragIndex(null);
    };

    // Handle edit form keydown
    const handleEditKeyDown = (e) => {
        if (e.key === 'Enter') {
            saveTabRename();
        } else if (e.key === 'Escape') {
            cancelTabRename();
        }
    };

    // If no tabs available, show placeholder
    if (allTabsInOrder.length === 0) {
        return (
            <div className={`wpuf-tab-manager wpuf-text-gray-400 wpuf-text-center wpuf-py-4 ${className}`}>
                {placeholder}
            </div>
        );
    }

    return (
        <div className={`wpuf-tab-manager ${className}`} ref={containerRef}>
            <div className="wpuf-tab-list">
                {allTabsInOrder.map((tabId, index) => (
                    <div
                        key={tabId}
                        className={`wpuf-tab-item ${editingTab === tabId ? 'wpuf-editing' : ''} ${!enabledTabs.includes(tabId) ? 'wpuf-tab-disabled' : ''}`}
                        draggable={sortable}
                        onDragStart={sortable ? (e) => handleDragStart(e, index) : undefined}
                        onDragOver={sortable ? (e) => handleDragOver(e, index) : undefined}
                        onDrop={sortable ? (e) => handleDrop(e, index) : undefined}
                        onDragEnd={sortable ? handleDragEnd : undefined}
                        data-index={index}
                    >
                        <div className="wpuf-tab-item-content">
                            {sortable && (
                                <div className="wpuf-tab-drag-handle">
                                    <span className="dashicons dashicons-menu"></span>
                                </div>
                            )}

                            <div className="wpuf-tab-info">
                                {editingTab === tabId ? (
                                    <div className="wpuf-tab-edit-form">
                                        <TextControl
                                            value={editValue}
                                            onChange={setEditValue}
                                            onKeyDown={handleEditKeyDown}
                                            __next40pxDefaultSize={true}
                                            __nextHasNoMarginBottom={true}
                                            autoFocus
                                        />
                                        <div className="wpuf-tab-edit-actions">
                                            <Button
                                                icon={check}
                                                label={__('Save', 'wpuf-pro')}
                                                onClick={saveTabRename}
                                                variant="primary"
                                                size="small"
                                            />
                                            <Button
                                                icon={close}
                                                label={__('Cancel', 'wpuf-pro')}
                                                onClick={cancelTabRename}
                                                variant="secondary"
                                                size="small"
                                            />
                                        </div>
                                    </div>
                                ) : (
                                    <div className="wpuf-tab-label">
                                        {getTabLabel(tabId, customLabels, availableTabs)}
                                        {editable && (
                                            <Button
                                                icon={edit}
                                                label={__('Rename', 'wpuf-pro')}
                                                onClick={() => handleTabRename(tabId)}
                                                variant="tertiary"
                                                size="small"
                                            />
                                        )}
                                    </div>
                                )}
                            </div>

                            <div className="wpuf-tab-toggle">
                                <ToggleControl
                                    checked={enabledTabs.includes(tabId)}
                                    onChange={(enabled) => handleTabToggle(tabId, enabled)}
                                    label=""
                                    __nextHasNoMarginBottom={true}
                                />
                            </div>
                        </div>
                    </div>
                ))}
            </div>

            <div className="wpuf-tab-summary">
                <p className="wpuf-text-sm wpuf-text-gray-600">
                    {__('Active tabs:', 'wpuf-pro')} {visibleTabs.length} / {allTabsInOrder.length}
                </p>
            </div>
        </div>
    );
};

export default TabManager;
