import React, { useState, useRef, useEffect } from 'react';
import { __ } from '@wordpress/i18n';

const DraggableTabsEditor = ({ options, value, onChange, savedOrder }) => {
    const [editingTab, setEditingTab] = useState(null);
    const [editValue, setEditValue] = useState('');
    const [draggedItem, setDraggedItem] = useState(null);
    const [dragOverItem, setDragOverItem] = useState(null);
    const [enabledTabs, setEnabledTabs] = useState(value || []);
    const [hoveredTab, setHoveredTab] = useState(null);
    const editInputRef = useRef(null);
    
    // Initialize tabs with saved order and custom labels
    const [allTabs, setAllTabs] = useState(() => {
        // First, create all tabs with their properties
        const tabsMap = {};
        Object.keys(options).forEach(key => {
            tabsMap[key] = {
                key,
                label: typeof options[key] === 'string' 
                    ? options[key] 
                    : options[key]?.label || options[key]?.default || key,
                customLabel: typeof options[key] === 'object' 
                    ? options[key]?.customLabel 
                    : undefined,
                enabled: value.includes(key)
            };
        });
        
        // Use savedOrder if available, otherwise fall back to enabled tabs order
        const orderedTabs = [];
        const orderToUse = savedOrder && savedOrder.length > 0 ? savedOrder : value;
        
        // First add tabs in their saved order
        if (orderToUse && orderToUse.length > 0) {
            orderToUse.forEach(key => {
                if (tabsMap[key]) {
                    orderedTabs.push(tabsMap[key]);
                    delete tabsMap[key];
                }
            });
        }
        
        // Then add remaining tabs that weren't in the saved order
        Object.values(tabsMap).forEach(tab => {
            orderedTabs.push(tab);
        });
        
        return orderedTabs;
    });

    // Focus input when editing starts
    useEffect(() => {
        if (editingTab !== null && editInputRef.current) {
            editInputRef.current.focus();
            editInputRef.current.select();
        }
    }, [editingTab]);
    
    // Save any pending edits when component unmounts or value changes
    useEffect(() => {
        return () => {
            // Save any pending edit when unmounting
            if (editingTab !== null && editValue) {
                const updatedTabs = allTabs.map(tab => 
                    tab.key === editingTab 
                        ? { ...tab, customLabel: editValue }
                        : tab
                );
                
                // Update the options with custom label
                const updatedOptions = { ...options };
                if (typeof updatedOptions[editingTab] === 'object') {
                    updatedOptions[editingTab].customLabel = editValue;
                } else {
                    updatedOptions[editingTab] = {
                        label: updatedOptions[editingTab],
                        customLabel: editValue
                    };
                }
                
                // Trigger onChange with updated value
                const completeOrder = allTabs.map(t => t.key);
                onChange(enabledTabs, updatedOptions, completeOrder);
            }
        };
    }, [editingTab, editValue, enabledTabs, allTabs, options, onChange]);

    // Start editing a tab
    const startEdit = (key) => {
        const tab = allTabs.find(t => t.key === key);
        setEditingTab(key);
        setEditValue(tab?.customLabel || tab?.label || key);
    };

    // Save edited tab
    const saveEdit = () => {
        if (editingTab !== null) {
            const updatedTabs = allTabs.map(tab => 
                tab.key === editingTab 
                    ? { ...tab, customLabel: editValue }
                    : tab
            );
            setAllTabs(updatedTabs);
            
            // Update the options with custom label
            const updatedOptions = { ...options };
            if (typeof updatedOptions[editingTab] === 'object') {
                updatedOptions[editingTab].customLabel = editValue;
            } else {
                updatedOptions[editingTab] = {
                    label: updatedOptions[editingTab],
                    customLabel: editValue
                };
            }
            
            // Trigger onChange with updated value
            const completeOrder = allTabs.map(t => t.key);
            onChange(enabledTabs, updatedOptions, completeOrder);
            setEditingTab(null);
            setEditValue('');
        }
    };

    // Cancel editing
    const cancelEdit = () => {
        setEditingTab(null);
        setEditValue('');
    };

    // Handle key press in edit input
    const handleEditKeyDown = (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            saveEdit();
        } else if (e.key === 'Escape') {
            cancelEdit();
        }
    };

    // Toggle tab enable/disable
    const toggleTab = (key) => {
        // Save any pending edits first
        if (editingTab !== null) {
            saveEdit();
        }
        
        let newEnabledTabs;
        if (enabledTabs.includes(key)) {
            newEnabledTabs = enabledTabs.filter(k => k !== key);
        } else {
            // Add in the same position as it appears in allTabs
            const tabIndex = allTabs.findIndex(t => t.key === key);
            const enabledBefore = allTabs.slice(0, tabIndex).filter(t => enabledTabs.includes(t.key));
            const insertPosition = enabledBefore.length;
            newEnabledTabs = [...enabledTabs];
            newEnabledTabs.splice(insertPosition, 0, key);
        }
        setEnabledTabs(newEnabledTabs);
        
        // Update allTabs to reflect the new enabled state
        const updatedAllTabs = allTabs.map(tab => 
            tab.key === key ? { ...tab, enabled: !tab.enabled } : tab
        );
        setAllTabs(updatedAllTabs);
        
        // Build updated options to pass custom labels
        const updatedOptions = { ...options };
        updatedAllTabs.forEach(tab => {
            if (tab.customLabel) {
                if (typeof updatedOptions[tab.key] === 'object') {
                    updatedOptions[tab.key].customLabel = tab.customLabel;
                } else {
                    updatedOptions[tab.key] = {
                        label: updatedOptions[tab.key],
                        customLabel: tab.customLabel
                    };
                }
            }
        });
        
        const completeOrder = allTabs.map(t => t.key);
        onChange(newEnabledTabs, updatedOptions, completeOrder);
    };


    // Drag and drop handlers
    const handleDragStart = (e, index) => {
        setDraggedItem(index);
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/html', e.target.innerHTML);
    };

    const handleDragEnd = (e) => {
        e.preventDefault();
        setDraggedItem(null);
        setDragOverItem(null);
    };

    const handleDragOver = (e) => {
        if (e.preventDefault) {
            e.preventDefault();
        }
        e.dataTransfer.dropEffect = 'move';
        return false;
    };

    const handleDragEnter = (e, index) => {
        if (draggedItem !== index) {
            setDragOverItem(index);
        }
    };

    const handleDragLeave = (e) => {
        if (e.target === e.currentTarget) {
            setDragOverItem(null);
        }
    };

    const handleDrop = (e, dropIndex) => {
        if (e.stopPropagation) {
            e.stopPropagation();
        }
        e.preventDefault();
        
        if (draggedItem !== null && draggedItem !== dropIndex) {
            const newTabs = [...allTabs];
            const draggedTab = newTabs[draggedItem];
            
            // Remove from old position and insert at new position
            newTabs.splice(draggedItem, 1);
            newTabs.splice(dropIndex, 0, draggedTab);
            
            setAllTabs(newTabs);
            
            // Update enabled tabs order based on new tab positions
            const newEnabledOrder = newTabs
                .filter(t => enabledTabs.includes(t.key))
                .map(t => t.key);
            
            setEnabledTabs(newEnabledOrder);
            
            // Build updated options to pass custom labels with new order
            const updatedOptions = {};
            newTabs.forEach((tab, index) => {
                const originalOption = options[tab.key];
                if (typeof originalOption === 'object') {
                    updatedOptions[tab.key] = {
                        ...originalOption,
                        customLabel: tab.customLabel
                    };
                } else {
                    updatedOptions[tab.key] = tab.customLabel 
                        ? { label: originalOption, customLabel: tab.customLabel }
                        : originalOption;
                }
            });
            
            // Call onChange with the new order, updated options, and complete tabs order
            const completeOrder = newTabs.map(t => t.key);
            onChange(newEnabledOrder, updatedOptions, completeOrder);
        }
        
        setDraggedItem(null);
        setDragOverItem(null);
        
        return false;
    };

    return (
        <div className="wpuf-draggable-tabs-editor">
            <div className="wpuf-space-y-2">
                {allTabs.map((tab, index) => {
                    const isEditing = editingTab === tab.key;
                    const isEnabled = enabledTabs.includes(tab.key);
                    const isDragging = draggedItem === index;
                    const isDragOver = dragOverItem === index;
                    
                    return (
                        <div
                            key={tab.key}
                            className={`
                                wpuf-flex wpuf-items-center wpuf-justify-between 
                                wpuf-bg-white wpuf-border wpuf-rounded-md 
                                wpuf-px-4 wpuf-py-4 wpuf-h-[52px] wpuf-w-full
                                wpuf-transition-all wpuf-cursor-move
                                ${isDragging ? 'wpuf-opacity-50 wpuf-scale-[0.98]' : ''}
                                ${isDragOver ? 'wpuf-border-emerald-500 wpuf-bg-emerald-50' : 'wpuf-border-gray-200'}
                            `}
                            draggable={!isEditing}
                            onDragStart={(e) => handleDragStart(e, index)}
                            onDragEnd={handleDragEnd}
                            onDragOver={handleDragOver}
                            onDragEnter={(e) => handleDragEnter(e, index)}
                            onDragLeave={handleDragLeave}
                            onDrop={(e) => handleDrop(e, index)}
                            onMouseEnter={() => setHoveredTab(tab.key)}
                            onMouseLeave={() => setHoveredTab(null)}
                        >
                            <div className="wpuf-flex wpuf-items-center wpuf-flex-1">
                                {/* Drag Handle */}
                                <svg className="wpuf-w-5 wpuf-h-5 wpuf-mr-4 wpuf-cursor-move" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path d="M3.125 5.625H16.875M3.125 10H16.875M3.125 14.375H16.875" stroke="#9CA3AF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                </svg>
                                
                                {/* Tab Name or Edit Input */}
                                {isEditing ? (
                                    <input
                                        ref={editInputRef}
                                        type="text"
                                        className="wpuf-text-[15px] wpuf-text-gray-700 wpuf-font-medium wpuf-border wpuf-border-emerald-500 wpuf-rounded wpuf-px-2 wpuf-py-1 wpuf-bg-white wpuf-outline-none wpuf-min-w-[200px]"
                                        value={editValue}
                                        onChange={(e) => setEditValue(e.target.value)}
                                        onKeyDown={handleEditKeyDown}
                                        onBlur={saveEdit}
                                        onClick={(e) => e.stopPropagation()}
                                    />
                                ) : (
                                    <span className="wpuf-text-[15px] wpuf-text-gray-700 wpuf-font-medium wpuf-min-w-[120px]">
                                        {tab.customLabel || tab.label}
                                    </span>
                                )}
                            </div>
                            
                            <div className="wpuf-flex wpuf-items-center wpuf-gap-3">
                                {/* Edit/Save/Cancel Actions */}
                                {isEditing ? (
                                    <div className="wpuf-flex wpuf-gap-2">
                                        <button 
                                            className="wpuf-p-1 wpuf-rounded hover:wpuf-bg-emerald-50 wpuf-transition-colors"
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                saveEdit();
                                            }}
                                        >
                                            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M4.16699 10.8333L7.50033 14.1666L15.8337 5.83325" stroke="#059669" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                            </svg>
                                        </button>
                                        <button 
                                            className="wpuf-p-1 wpuf-rounded hover:wpuf-bg-gray-50 wpuf-transition-colors"
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                cancelEdit();
                                            }}
                                        >
                                            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M5 15L15 5M5 5L15 15" stroke="#4B5563" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                            </svg>
                                        </button>
                                    </div>
                                ) : (
                                    <svg 
                                        className={`wpuf-w-[18px] wpuf-h-[18px] wpuf-cursor-pointer wpuf-transition-all ${hoveredTab === tab.key ? 'wpuf-opacity-100' : 'wpuf-opacity-0'}`}
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            startEdit(tab.key);
                                        }}
                                        viewBox="0 0 18 18"
                                        fill="none"
                                        xmlns="http://www.w3.org/2000/svg"
                                    >
                                        <path d="M15.8898 2.11019L16.4201 1.57986V1.57986L15.8898 2.11019ZM4.41667 16.5296V17.2796C4.61558 17.2796 4.80634 17.2005 4.947 17.0599L4.41667 16.5296ZM1.5 16.5296H0.75C0.75 16.9438 1.08579 17.2796 1.5 17.2796L1.5 16.5296ZM1.5 13.5537L0.96967 13.0233C0.829018 13.164 0.75 13.3548 0.75 13.5537H1.5ZM12.9435 2.11019L13.4738 2.64052C13.9945 2.11983 14.8387 2.11983 15.3594 2.64052L15.8898 2.11019L16.4201 1.57986C15.3136 0.473379 13.5196 0.473379 12.4132 1.57986L12.9435 2.11019ZM15.8898 2.11019L15.3594 2.64052C15.8801 3.16122 15.8801 4.00544 15.3594 4.52614L15.8898 5.05647L16.4201 5.5868C17.5266 4.48032 17.5266 2.68635 16.4201 1.57986L15.8898 2.11019ZM15.8898 5.05647L15.3594 4.52614L3.88634 15.9992L4.41667 16.5296L4.947 17.0599L16.4201 5.5868L15.8898 5.05647ZM4.41667 16.5296V15.7796H1.5V16.5296V17.2796H4.41667V16.5296ZM12.9435 2.11019L12.4132 1.57986L0.96967 13.0233L1.5 13.5537L2.03033 14.084L13.4738 2.64052L12.9435 2.11019ZM1.5 13.5537H0.75V16.5296H1.5H2.25V13.5537H1.5ZM11.6935 3.36019L11.1632 3.89052L14.1094 6.8368L14.6398 6.30647L15.1701 5.77614L12.2238 2.82986L11.6935 3.36019Z" fill="#6B7280"/>
                                    </svg>
                                )}
                                
                                {/* Toggle Switch */}
                                <label className="wpuf-relative wpuf-inline-flex wpuf-items-center wpuf-cursor-pointer">
                                    <input 
                                        type="checkbox" 
                                        className="wpuf-sr-only wpuf-peer"
                                        checked={isEnabled}
                                        onChange={() => toggleTab(tab.key)}
                                    />
                                    <div 
                                        className="wpuf-relative wpuf-inline-block wpuf-transition-colors"
                                        style={{
                                            width: '36px',
                                            height: '16px',
                                            borderRadius: '8px',
                                            backgroundColor: isEnabled ? '#059669' : '#D1D5DB',
                                            opacity: 1
                                        }}
                                    >
                                        <span 
                                            className="wpuf-absolute wpuf-transition-all"
                                            style={{
                                                width: '20px',
                                                height: '20px',
                                                borderRadius: '50%',
                                                backgroundColor: '#FFFFFF',
                                                border: '1px solid #D1D5DB',
                                                boxShadow: '0px 1px 2px 0px #0000000F, 0px 1px 3px 0px #0000001A',
                                                top: '-2px',
                                                left: isEnabled ? '16px' : '0px',
                                                opacity: 1
                                            }}
                                        />
                                    </div>
                                </label>
                            </div>
                        </div>
                    );
                })}
            </div>
        </div>
    );
};

export default DraggableTabsEditor;