import React, { useState, useEffect } from 'react';
import {
  CollaborationProvider,
  UserPresence,
  CollaborativeTaskForm,
  ChangeHistory,
  SnapshotManager,
  VersionComparison,
  RollbackConfirmation,
  AwarenessIndicator
} from '../components';

// Comprehensive demo showcasing all collaboration features
export const FullCollaborationDemo: React.FC = () => {
  const [activeView, setActiveView] = useState<'form' | 'history' | 'snapshots'>('form');
  const [showComparison, setShowComparison] = useState(false);
  const [showRollback, setShowRollback] = useState(false);
  
  // Mock data for demonstration
  const mockUser = {
    id: 'demo-user',
    name: 'Demo User',
    email: 'demo@example.com',
    color: '#6C5CE7'
  };

  const mockChanges = [
    {
      id: 'change-1',
      userId: 'user1',
      userName: 'Alice Johnson',
      timestamp: new Date(Date.now() - 10 * 60 * 1000),
      field: 'title',
      oldValue: 'Initial Task',
      newValue: 'Comprehensive Collaboration Task',
      type: 'update' as const,
      metadata: { source: 'collaborative-form' }
    },
    {
      id: 'change-2',
      userId: 'user2',
      userName: 'Bob Smith',
      timestamp: new Date(Date.now() - 20 * 60 * 1000),
      field: 'description',
      oldValue: 'Basic description',
      newValue: 'Detailed description with collaboration features including real-time editing, presence indicators, and change tracking.',
      type: 'update' as const,
      metadata: { source: 'api' }
    },
    {
      id: 'change-3',
      userId: 'user1',
      userName: 'Alice Johnson',
      timestamp: new Date(Date.now() - 30 * 60 * 1000),
      field: 'status',
      oldValue: 'pending',
      newValue: 'in-progress',
      type: 'update' as const,
      metadata: { source: 'status-change' }
    }
  ];

  const mockSnapshots = [
    {
      id: 'snapshot-1',
      name: 'Current Working Version',
      description: 'Latest version with all collaboration features',
      timestamp: new Date(Date.now() - 30 * 60 * 1000),
      userId: 'demo-user',
      userName: 'Demo User',
      data: {
        title: 'Comprehensive Collaboration Task',
        description: 'Detailed description with collaboration features including real-time editing, presence indicators, and change tracking.',
        status: 'in-progress',
        priority: 'high',
        assignees: ['user1', 'user2'],
        tags: ['collaboration', 'demo', 'y.js', 'real-time']
      },
      size: 1456,
      isAutomatic: false
    },
    {
      id: 'snapshot-2',
      name: 'Auto: Before Priority Change',
      description: 'Automatic snapshot before priority was changed to high',
      timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000),
      userId: 'system',
      userName: 'System',
      data: {
        title: 'Comprehensive Collaboration Task',
        description: 'Basic description with collaboration features',
        status: 'in-progress',
        priority: 'medium',
        assignees: ['user1'],
        tags: ['collaboration', 'demo']
      },
      size: 1234,
      isAutomatic: true
    }
  ];

  const mockVersions = {
    versionA: {
      id: 'current',
      timestamp: new Date(),
      userId: 'demo-user',
      userName: 'Demo User',
      data: mockSnapshots[0].data,
      changeCount: 12
    },
    versionB: {
      id: 'previous',
      timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000),
      userId: 'system',
      userName: 'System',
      data: mockSnapshots[1].data,
      changeCount: 8
    }
  };

  // Handlers
  const handleSaveTask = (taskData: any) => {
    console.log('Task saved:', taskData);
    alert('✅ Task saved successfully with real-time collaboration!');
  };

  const handleRevert = (changeId: string) => {
    console.log('Reverting change:', changeId);
    alert(`🔄 Reverted change ${changeId}`);
  };

  const handleCompare = (id1: string, id2: string) => {
    console.log('Comparing:', id1, id2);
    setShowComparison(true);
  };

  const handleCreateSnapshot = async (name: string, description?: string) => {
    console.log('Creating snapshot:', { name, description });
    alert(`📸 Created snapshot: ${name}`);
  };

  const handleRestoreSnapshot = async (snapshotId: string) => {
    console.log('Restoring snapshot:', snapshotId);
    setShowRollback(true);
  };

  const handleDeleteSnapshot = async (snapshotId: string) => {
    console.log('Deleting snapshot:', snapshotId);
    alert(`🗑️ Deleted snapshot: ${snapshotId}`);
  };

  const handleCompareSnapshots = (id1: string, id2: string) => {
    console.log('Comparing snapshots:', id1, id2);
    setShowComparison(true);
  };

  const handleRollbackConfirm = (createBackup: boolean) => {
    console.log('Rollback confirmed, backup:', createBackup);
    alert('✅ Rollback completed successfully!');
    setShowRollback(false);
  };

  return (
    <CollaborationProvider
      options={{
        documentId: 'full-demo-doc',
        documentType: 'task',
        userId: mockUser.id,
        userInfo: mockUser,
        serverUrl: 'http://localhost:3000',
        onUserJoined: (user) => console.log('User joined:', user),
        onUserLeft: (userId) => console.log('User left:', userId),
        onCursorUpdate: (userId, cursor) => console.log('Cursor update:', { userId, cursor }),
        onAwarenessUpdate: (userId, awareness) => console.log('Awareness:', { userId, awareness }),
        onDocumentChange: (event) => console.log('Document changed:', event),
        autoConnect: true
      }}
    >
      <div className="full-collaboration-demo">
        <div className="demo-header">
          <h1>🚀 Complete Collaboration System Demo</h1>
          <p>Experience all real-time collaboration features in action</p>
          
          {/* User Presence Bar */}
          <div className="demo-presence-bar">
            <UserPresence
              users={[
                mockUser,
                {
                  id: 'user1',
                  name: 'Alice Johnson',
                  color: '#FF6B6B',
                  cursor: { field: 'title', position: 15 }
                },
                {
                  id: 'user2',
                  name: 'Bob Smith',
                  color: '#4ECDC4',
                  cursor: { field: 'description', position: 42 }
                },
                {
                  id: 'user3',
                  name: 'Carol Davis',
                  color: '#45B7D1'
                }
              ]}
              maxDisplay={6}
              showCursors={true}
            />
          </div>
        </div>

        {/* Navigation */}
        <div className="demo-navigation">
          <button
            className={`nav-tab ${activeView === 'form' ? 'active' : ''}`}
            onClick={() => setActiveView('form')}
          >
            📝 Collaborative Form
          </button>
          <button
            className={`nav-tab ${activeView === 'history' ? 'active' : ''}`}
            onClick={() => setActiveView('history')}
          >
            📊 Change History
          </button>
          <button
            className={`nav-tab ${activeView === 'snapshots' ? 'active' : ''}`}
            onClick={() => setActiveView('snapshots')}
          >
            📸 Snapshots
          </button>
        </div>

        {/* Main Content */}
        <div className="demo-content">
          {activeView === 'form' && (
            <div className="demo-section">
              <div className="demo-section-header">
                <h2>Real-time Collaborative Task Form</h2>
                <AwarenessIndicator
                  section="task-form"
                  awareness={[
                    {
                      userId: 'user1',
                      userName: 'Alice Johnson',
                      color: '#FF6B6B',
                      section: 'task-form',
                      activity: 'editing' as const,
                      lastActivity: new Date()
                    }
                  ]}
                  currentUserId={mockUser.id}
                  position="right"
                />
              </div>
              
              <div className="demo-features">
                <div className="feature-badge">✨ Real-time Editing</div>
                <div className="feature-badge">👥 User Presence</div>
                <div className="feature-badge">🎯 Cursor Tracking</div>
                <div className="feature-badge">📡 Live Sync</div>
              </div>
              
              <CollaborativeTaskForm
                taskId="full-demo-task"
                initialData={{
                  title: 'Comprehensive Collaboration Task',
                  description: 'This task demonstrates all collaboration features including real-time editing, presence indicators, change tracking, and version management.',
                  status: 'in-progress',
                  priority: 'high'
                }}
                onSave={handleSaveTask}
              />
            </div>
          )}

          {activeView === 'history' && (
            <div className="demo-section">
              <div className="demo-section-header">
                <h2>Comprehensive Change History</h2>
                <AwarenessIndicator
                  section="change-history"
                  awareness={[]}
                  currentUserId={mockUser.id}
                  position="right"
                />
              </div>
              
              <div className="demo-features">
                <div className="feature-badge">🔍 Advanced Filtering</div>
                <div className="feature-badge">📈 Visual Diffs</div>
                <div className="feature-badge">↩️ One-click Revert</div>
                <div className="feature-badge">⚖️ Version Comparison</div>
              </div>
              
              <ChangeHistory
                changes={mockChanges}
                onRevert={handleRevert}
                onCompare={handleCompare}
                maxDisplay={50}
                showDiff={true}
              />
            </div>
          )}

          {activeView === 'snapshots' && (
            <div className="demo-section">
              <div className="demo-section-header">
                <h2>Advanced Snapshot Management</h2>
                <AwarenessIndicator
                  section="snapshots"
                  awareness={[]}
                  currentUserId={mockUser.id}
                  position="right"
                />
              </div>
              
              <div className="demo-features">
                <div className="feature-badge">📸 Manual Snapshots</div>
                <div className="feature-badge">🤖 Auto Snapshots</div>
                <div className="feature-badge">🔄 Smart Restore</div>
                <div className="feature-badge">📊 Size Tracking</div>
              </div>
              
              <SnapshotManager
                documentId="full-demo-doc"
                snapshots={mockSnapshots}
                onCreateSnapshot={handleCreateSnapshot}
                onRestoreSnapshot={handleRestoreSnapshot}
                onDeleteSnapshot={handleDeleteSnapshot}
                onCompareSnapshots={handleCompareSnapshots}
                isLoading={false}
              />
            </div>
          )}
        </div>

        {/* Modals */}
        {showComparison && (
          <div className="modal-overlay" onClick={() => setShowComparison(false)}>
            <div className="modal-content" onClick={(e) => e.stopPropagation()}>
              <VersionComparison
                versionA={mockVersions.versionA}
                versionB={mockVersions.versionB}
                onRestore={(versionId) => {
                  console.log('Restore version:', versionId);
                  alert(`Restored to version ${versionId}`);
                  setShowComparison(false);
                }}
                onClose={() => setShowComparison(false)}
              />
            </div>
          </div>
        )}

        {showRollback && (
          <RollbackConfirmation
            data={{
              targetVersion: {
                id: 'snapshot-2',
                timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000),
                userId: 'system',
                userName: 'System',
                changeCount: 8
              },
              currentVersion: {
                id: 'current',
                timestamp: new Date(),
                userId: 'demo-user',
                userName: 'Demo User',
                changeCount: 12
              },
              affectedFields: ['priority', 'assignees', 'tags', 'description'],
              conflictingUsers: ['Alice Johnson', 'Bob Smith']
            }}
            onConfirm={handleRollbackConfirm}
            onCancel={() => setShowRollback(false)}
            isLoading={false}
          />
        )}

        {/* Footer Stats */}
        <div className="demo-footer">
          <div className="demo-stats">
            <div className="stat-item">
              <strong>4</strong> Active Users
            </div>
            <div className="stat-item">
              <strong>23</strong> Total Changes
            </div>
            <div className="stat-item">
              <strong>3</strong> Snapshots
            </div>
            <div className="stat-item">
              <strong>🟢</strong> Connected
            </div>
          </div>
        </div>
        
        <style jsx>{`
          .full-collaboration-demo {
            max-width: 1200px;
            margin: 0 auto;
            padding: 24px;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
          }
          
          .demo-header {
            text-align: center;
            margin-bottom: 32px;
            padding: 24px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 16px;
            color: white;
          }
          
          .demo-header h1 {
            margin: 0 0 8px 0;
            font-size: 32px;
            font-weight: 700;
          }
          
          .demo-header p {
            margin: 0 0 20px 0;
            font-size: 16px;
            opacity: 0.9;
          }
          
          .demo-presence-bar {
            display: flex;
            justify-content: center;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: 50px;
            padding: 12px 24px;
            margin-top: 16px;
          }
          
          .demo-navigation {
            display: flex;
            justify-content: center;
            gap: 4px;
            margin-bottom: 32px;
            background: #f8f9fa;
            padding: 8px;
            border-radius: 12px;
          }
          
          .nav-tab {
            padding: 12px 24px;
            border: none;
            background: transparent;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            color: #666;
          }
          
          .nav-tab:hover {
            background: rgba(78, 205, 196, 0.1);
            color: #4ECDC4;
          }
          
          .nav-tab.active {
            background: #4ECDC4;
            color: white;
            box-shadow: 0 2px 8px rgba(78, 205, 196, 0.3);
          }
          
          .demo-content {
            margin-bottom: 32px;
          }
          
          .demo-section {
            background: white;
            border-radius: 16px;
            padding: 32px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(0, 0, 0, 0.05);
          }
          
          .demo-section-header {
            position: relative;
            margin-bottom: 24px;
          }
          
          .demo-section-header h2 {
            margin: 0;
            color: #333;
            font-size: 24px;
            font-weight: 700;
          }
          
          .demo-features {
            display: flex;
            gap: 8px;
            margin-bottom: 24px;
            flex-wrap: wrap;
          }
          
          .feature-badge {
            background: #e3f2fd;
            color: #1976d2;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            border: 1px solid rgba(25, 118, 210, 0.2);
          }
          
          .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.6);
            backdrop-filter: blur(4px);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            padding: 20px;
          }
          
          .modal-content {
            max-width: 90vw;
            max-height: 90vh;
            overflow: auto;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
          }
          
          .demo-footer {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            border: 2px dashed #e0e0e0;
          }
          
          .demo-stats {
            display: flex;
            justify-content: center;
            gap: 32px;
            flex-wrap: wrap;
          }
          
          .stat-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            font-size: 14px;
            color: #666;
          }
          
          .stat-item strong {
            font-size: 20px;
            color: #4ECDC4;
            margin-bottom: 4px;
          }
          
          @media (max-width: 768px) {
            .full-collaboration-demo {
              padding: 16px;
            }
            
            .demo-header {
              padding: 20px 16px;
            }
            
            .demo-header h1 {
              font-size: 24px;
            }
            
            .demo-navigation {
              flex-direction: column;
              align-items: center;
            }
            
            .nav-tab {
              width: 100%;
              max-width: 280px;
            }
            
            .demo-section {
              padding: 20px;
            }
            
            .demo-stats {
              flex-direction: column;
              gap: 16px;
            }
            
            .demo-features {
              justify-content: center;
            }
          }
        `}</style>
      </div>
    </CollaborationProvider>
  );
};