const VersionHistoryPanel = ({ article, historyVersions, versions: versionsProp, onRestore, onClose, versioningMode, isOpen }) => {
    const [selectedVersion, setSelectedVersion] = React.useState(null);
    const [showRestoreConfirm, setShowRestoreConfirm] = React.useState(false);

    const versions = Array.isArray(versionsProp) ? versionsProp : (Array.isArray(historyVersions) ? historyVersions : []);
    const isHistoryMode = versioningMode === 'history';
    const isParallelMode = versioningMode === 'parallel';

    React.useEffect(() => {
        if (versions.length > 0 && !selectedVersion) {
            setSelectedVersion(versions[0]);
        }
    }, [versions.length]);

    const formatFileSize = (bytes) => {
        if (!bytes) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return (bytes / Math.pow(k, i)).toFixed(1) + ' ' + sizes[i];
    };

    const getAttachments = (version) => {
        if (version.attachments_snapshot) {
            try {
                return typeof version.attachments_snapshot === 'string'
                    ? JSON.parse(version.attachments_snapshot)
                    : version.attachments_snapshot;
            } catch (e) {
                return version.attachments || [];
            }
        }
        return version.attachments || [];
    };

    const handleRestore = async () => {
        if (!selectedVersion || selectedVersion.is_current) return;
        try {
            await onRestore(selectedVersion.id);
            setShowRestoreConfirm(false);
            onClose();
        } catch (error) {
            console.error('Restore error:', error);
            window.otoNotify?.toast('Failed to restore version', 'error');
        }
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-xl max-w-6xl w-full h-[85vh] overflow-hidden shadow-2xl flex flex-col">
                {/* Header with gradient */}
                <div className="bg-gradient-to-r from-primary to-primary-hover px-6 py-4 flex items-center justify-between">
                    <div>
                        <h2 className="text-xl font-bold text-white">
                            {isParallelMode ? 'Parallel Versions' : 'Version History'}
                        </h2>
                        <p className="text-sm text-white/80 mt-1">
                            {isParallelMode ? 'All versions work together' : 'Track changes and restore previous versions'}
                        </p>
                    </div>
                    <button
                        onClick={onClose}
                        className="text-white/80 hover:text-white transition-colors p-1"
                    >
                        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>

                {/* Content Area */}
                <div className="flex-1 flex overflow-hidden">
                    {/* Left Sidebar - Version List */}
                    <div className="w-80 border-r border-gray-200 flex flex-col bg-gray-50">
                        <div className="px-6 py-4 border-b border-gray-200 bg-white">
                            <h3 className="font-semibold text-gray-900">
                                {isParallelMode ? 'All Versions' : 'Timeline'}
                            </h3>
                            <p className="text-xs text-gray-500 mt-1">
                                {versions.length} version{versions.length !== 1 ? 's' : ''}
                            </p>
                        </div>

                        <div className="flex-1 overflow-y-auto">
                            {versions.length === 0 ? (
                                <div className="p-8 text-center">
                                    <div className="text-4xl mb-3">📄</div>
                                    <p className="text-sm text-gray-600">No versions found</p>
                                </div>
                            ) : (
                                versions.map((version, index) => {
                                    const isSelected = selectedVersion?.id === version.id || selectedVersion?.version === version.version;
                                    const isCurrent = version.is_current || index === 0;

                                    return (
                                        <div
                                            key={version.id || version.version}
                                            onClick={() => setSelectedVersion(version)}
                                            className={`px-6 py-4 border-b border-gray-100 cursor-pointer transition-colors ${isSelected
                                                    ? 'bg-primary/5 border-l-4 border-l-primary'
                                                    : 'hover:bg-white border-l-4 border-l-transparent'
                                                }`}
                                        >
                                            <div className="flex items-center justify-between mb-2">
                                                <span className="text-sm font-semibold text-gray-900">
                                                    Version {version.version}
                                                </span>
                                                <span className="flex items-center gap-1.5 flex-wrap justify-end">
                                                    {version.restored_from_version != null && (
                                                        <span className="text-xs px-2 py-0.5 bg-primary/10 text-primary rounded font-medium border border-primary/20">
                                                            Restored from v{version.restored_from_version}
                                                        </span>
                                                    )}
                                                    {isCurrent && (
                                                        <span className="text-xs px-2 py-0.5 bg-primary text-white rounded font-medium">
                                                            CURRENT
                                                        </span>
                                                    )}
                                                </span>
                                            </div>
                                            <div className="text-xs text-gray-600">
                                                {version.changed_by_name || version.changed_by}
                                            </div>
                                            <div className="text-xs text-gray-500 mt-1">
                                                {new Date(version.changed_at || version.modified_at).toLocaleDateString('en-US', {
                                                    month: 'short',
                                                    day: 'numeric',
                                                    year: 'numeric',
                                                    hour: 'numeric',
                                                    minute: '2-digit'
                                                })}
                                            </div>
                                        </div>
                                    );
                                })
                            )}
                        </div>
                    </div>

                    {/* Right Panel - Version Details */}
                    <div className="flex-1 flex flex-col bg-white">
                        {selectedVersion ? (
                            <>
                                <div className="px-6 py-4 border-b border-gray-200">
                                    <div className="flex items-start justify-between">
                                        <div className="flex-1">
                                            <div className="flex items-center gap-3 mb-2 flex-wrap">
                                                <h3 className="text-xl font-bold text-gray-900">
                                                    Version {selectedVersion.version}
                                                </h3>
                                                {selectedVersion.restored_from_version != null && (
                                                    <span className="text-xs px-2 py-1 bg-primary/10 text-primary rounded font-medium border border-primary/20">
                                                        Restored from v{selectedVersion.restored_from_version}
                                                    </span>
                                                )}
                                                {selectedVersion.is_current && (
                                                    <span className="text-xs px-2 py-1 bg-primary text-white rounded font-medium">
                                                        CURRENT
                                                    </span>
                                                )}
                                            </div>
                                            <p className="text-sm text-gray-600">
                                                {selectedVersion.changed_by_name || selectedVersion.changed_by} • {' '}
                                                {new Date(selectedVersion.changed_at || selectedVersion.modified_at).toLocaleString('en-US', {
                                                    month: 'long',
                                                    day: 'numeric',
                                                    year: 'numeric',
                                                    hour: 'numeric',
                                                    minute: '2-digit'
                                                })}
                                            </p>
                                        </div>
                                        {isHistoryMode && !selectedVersion.is_current && (
                                            <button
                                                onClick={() => setShowRestoreConfirm(true)}
                                                className="px-4 py-2 bg-primary hover:bg-primary-hover text-white text-sm font-semibold rounded-lg transition-colors shadow-sm"
                                            >
                                                Restore Version
                                            </button>
                                        )}
                                    </div>
                                </div>

                                <div className="flex-1 overflow-y-auto px-6 py-6">
                                    <div className="space-y-6">
                                        <div>
                                            <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">
                                                Title
                                            </label>
                                            <div className="text-base font-semibold text-gray-900">
                                                {selectedVersion.title}
                                            </div>
                                        </div>

                                        {selectedVersion.content && (
                                            <div>
                                                <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">
                                                    Content
                                                </label>
                                                <div className="bg-gray-50 rounded-lg border border-gray-200 p-4">
                                                    <div className="text-sm text-gray-700 whitespace-pre-wrap">
                                                        {selectedVersion.content}
                                                    </div>
                                                </div>
                                            </div>
                                        )}

                                        <div className="grid grid-cols-2 gap-6">
                                            {selectedVersion.category && (
                                                <div>
                                                    <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">
                                                        Category
                                                    </label>
                                                    <div className="text-sm text-gray-900">{selectedVersion.category}</div>
                                                </div>
                                            )}
                                            {selectedVersion.status && (
                                                <div>
                                                    <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">
                                                        Status
                                                    </label>
                                                    <div className="text-sm text-gray-900 capitalize">{selectedVersion.status}</div>
                                                </div>
                                            )}
                                        </div>

                                        {selectedVersion.tags && selectedVersion.tags.length > 0 && (
                                            <div>
                                                <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">
                                                    Tags
                                                </label>
                                                <div className="flex flex-wrap gap-2">
                                                    {selectedVersion.tags.map((tag, i) => (
                                                        <span key={i} className="oto-tag px-3 py-1 bg-primary/10 text-primary text-sm rounded-full font-medium border border-primary/20">
                                                            {tag}
                                                        </span>
                                                    ))}
                                                </div>
                                            </div>
                                        )}

                                        {(() => {
                                            const attachments = getAttachments(selectedVersion);
                                            if (!attachments || attachments.length === 0) return null;

                                            return (
                                                <div>
                                                    <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">
                                                        Attachments
                                                    </label>
                                                    <div className="space-y-2">
                                                        {attachments.map((att, i) => (
                                                            <div key={i} className="bg-white rounded-lg border border-gray-200 p-4 flex items-center justify-between hover:border-primary/30 transition-colors">
                                                                <div className="flex items-center gap-3 flex-1 min-w-0">
                                                                    <div className="text-2xl">📎</div>
                                                                    <div className="flex-1 min-w-0">
                                                                        <div className="text-sm font-medium text-gray-900 truncate">
                                                                            {att.original_filename}
                                                                        </div>
                                                                        <div className="text-xs text-gray-500">
                                                                            {formatFileSize(att.file_size)}
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                {att.id && selectedVersion.kb_id && (
                                                                    <a
                                                                        href={`/api/knowledge-base/${selectedVersion.kb_id}/attachments/${att.id}/download`}
                                                                        target="_blank"
                                                                        rel="noopener noreferrer"
                                                                        className="px-3 py-1.5 bg-primary hover:bg-primary-hover text-white text-sm font-medium rounded transition-colors"
                                                                        onClick={(e) => e.stopPropagation()}
                                                                    >
                                                                        View
                                                                    </a>
                                                                )}
                                                            </div>
                                                        ))}
                                                    </div>
                                                </div>
                                            );
                                        })()}
                                    </div>
                                </div>
                            </>
                        ) : (
                            <div className="flex items-center justify-center h-full">
                                <div className="text-center">
                                    <div className="text-5xl mb-4">📄</div>
                                    <p className="text-base font-medium text-gray-900 mb-2">Select a version</p>
                                    <p className="text-sm text-gray-500">Click on any version in the timeline</p>
                                </div>
                            </div>
                        )}
                    </div>
                </div>

                {/* Restore Confirmation Modal */}
                {showRestoreConfirm && selectedVersion && !selectedVersion.is_current && (
                    <div className="absolute inset-0 bg-black/40 flex items-center justify-center z-10">
                        <div className="bg-white rounded-xl shadow-2xl max-w-md w-full mx-4">
                            <div className="p-6">
                                <h3 className="text-xl font-bold text-gray-900 mb-2">
                                    Restore Version {selectedVersion.version}?
                                </h3>
                                <p className="text-sm text-gray-600 mb-6">
                                    This will restore the content from Version {selectedVersion.version} and make it the new current version.
                                </p>

                                <div className="bg-primary/5 border border-primary/20 rounded-lg p-4 mb-6">
                                    <p className="text-sm font-semibold text-primary mb-2">What will be restored:</p>
                                    <ul className="text-sm text-gray-700 space-y-1">
                                        <li>• Title: {selectedVersion.title}</li>
                                        <li>• Content ({(selectedVersion.content || '').length} characters)</li>
                                        <li>• Tags ({(selectedVersion.tags || []).length})</li>
                                        {selectedVersion.category && <li>• Category: {selectedVersion.category}</li>}
                                        {(() => {
                                            const attachments = getAttachments(selectedVersion);
                                            if (attachments.length > 0) {
                                                return <li>• Attachments ({attachments.length} file{attachments.length !== 1 ? 's' : ''})</li>;
                                            }
                                        })()}
                                    </ul>
                                </div>

                                <div className="flex gap-3">
                                    <button
                                        onClick={handleRestore}
                                        className="flex-1 px-4 py-2.5 bg-primary hover:bg-primary-hover text-white font-semibold rounded-lg transition-colors"
                                    >
                                        Yes, Restore
                                    </button>
                                    <button
                                        onClick={() => setShowRestoreConfirm(false)}
                                        className="flex-1 px-4 py-2.5 bg-white border border-gray-300 text-gray-700 font-medium rounded-lg hover:bg-gray-50 transition-colors"
                                    >
                                        Cancel
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

if (typeof window !== 'undefined') window.VersionHistoryPanel = VersionHistoryPanel;