import React, { useState } from 'react';
import {
  CollaborationProvider,
  UserPresence,
  CollaborativeField,
  AwarenessIndicator,
  CollaborativeTaskForm,
  CollaborativeSection,
  useCollaborationContext
} from '../components';

// Mock user data for demo
const DEMO_USERS = [
  {
    id: 'user1',
    name: 'Alice Johnson',
    email: 'alice@example.com',
    color: '#FF6B6B',
    cursor: { field: 'title', position: 5 }
  },
  {
    id: 'user2', 
    name: 'Bob Smith',
    email: 'bob@example.com',
    color: '#4ECDC4',
    cursor: { field: 'description', position: 12 }
  },
  {
    id: 'user3',
    name: 'Carol Davis', 
    email: 'carol@example.com',
    color: '#45B7D1'
  }
];

// Mock awareness data
const DEMO_AWARENESS = [
  {
    userId: 'user1',
    userName: 'Alice Johnson',
    color: '#FF6B6B',
    section: 'basic-info',
    activity: 'editing' as const,
    lastActivity: new Date()
  },
  {
    userId: 'user2',
    userName: 'Bob Smith', 
    color: '#4ECDC4',
    section: 'metadata',
    activity: 'viewing' as const,
    lastActivity: new Date(Date.now() - 60000)
  }
];

/**
 * Individual Demo Component
 */
const DemoContent: React.FC = () => {
  const collaboration = useCollaborationContext();
  const [demoText, setDemoText] = useState('');
  
  return (
    <div className="collaboration-demo__content">
      <h1>🤝 Real-time Collaboration Demo</h1>
      
      {/* User Presence Section */}
      <CollaborativeSection sectionId="presence-demo" className="demo-section">
        <h2>User Presence</h2>
        <p>Shows active users with avatars and typing indicators:</p>
        
        <div className="demo-showcase">
          <UserPresence 
            users={DEMO_USERS}
            maxDisplay={5}
            showCursors={true}
          />
        </div>
        
        <AwarenessIndicator
          section="presence-demo"
          awareness={DEMO_AWARENESS}
          currentUserId="current-user"
          position="right"
        />
      </CollaborativeSection>

      {/* Collaborative Text Fields */}
      <CollaborativeSection sectionId="fields-demo" className="demo-section">
        <h2>Collaborative Text Fields</h2>
        <p>Real-time editing with cursor tracking:</p>
        
        <div className="demo-showcase">
          <CollaborativeField
            fieldName="demo-field"
            value={demoText}
            onChange={setDemoText}
            onCursorChange={(pos, sel) => {
              console.log('Cursor moved:', pos, sel);
            }}
            cursors={[
              {
                userId: 'user1',
                field: 'demo-field',
                position: 10,
                color: '#FF6B6B',
                userName: 'Alice'
              }
            ]}
            placeholder="Type here to see collaboration in action..."
            multiline={true}
          />
        </div>
        
        <AwarenessIndicator
          section="fields-demo"
          awareness={DEMO_AWARENESS.filter(a => a.section === 'fields-demo')}
          currentUserId="current-user"
          position="right"
        />
      </CollaborativeSection>

      {/* Collaborative Task Form */}
      <CollaborativeSection sectionId="form-demo" className="demo-section">
        <h2>Collaborative Task Form</h2>
        <p>Complete form with real-time collaboration:</p>
        
        <div className="demo-showcase">
          <CollaborativeTaskForm
            taskId="demo-task"
            initialData={{
              title: 'Demo Task',
              description: 'This is a demonstration of collaborative editing',
              status: 'in-progress',
              priority: 'high'
            }}
            onSave={(data) => {
              console.log('Task saved:', data);
              alert('Task saved! Check the console for data.');
            }}
          />
        </div>
        
        <AwarenessIndicator
          section="form-demo"
          awareness={DEMO_AWARENESS}
          currentUserId="current-user"
          position="right"
        />
      </CollaborativeSection>

      {/* Connection Status */}
      <div className="demo-status">
        <h3>Connection Status</h3>
        <div className="status-grid">
          <div className="status-item">
            <strong>Connected:</strong> {collaboration.isConnected ? '✅ Yes' : '❌ No'}
          </div>
          <div className="status-item">
            <strong>Active Users:</strong> {collaboration.activeUsers.length}
          </div>
          <div className="status-item">
            <strong>Unsaved Changes:</strong> {collaboration.hasUnsavedChanges ? '⚠️ Yes' : '✅ No'}
          </div>
        </div>
      </div>
    </div>
  );
};

/**
 * Collaboration Demo Component
 * Demonstrates all collaboration features
 */
export const CollaborationDemo: React.FC = () => {
  return (
    <CollaborationProvider
      options={{
        documentId: 'demo-document',
        documentType: 'task',
        userId: 'current-user',
        userInfo: {
          id: 'current-user',
          name: 'Current User',
          email: 'user@example.com',
          color: '#6C5CE7'
        },
        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 update:', userId, awareness),
        onDocumentChange: (event) => console.log('Document changed:', event),
        autoConnect: true
      }}
    >
      <div className="collaboration-demo">
        <DemoContent />
        
        <style jsx>{`
          .collaboration-demo {
            padding: 24px;
            max-width: 1200px;
            margin: 0 auto;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
          }
          
          .collaboration-demo__content h1 {
            text-align: center;
            color: #333;
            margin-bottom: 32px;
            font-size: 32px;
          }
          
          .demo-section {
            margin-bottom: 48px;
            padding: 24px;
            border: 1px solid #e0e0e0;
            border-radius: 12px;
            background: white;
            position: relative;
          }
          
          .demo-section h2 {
            color: #4ECDC4;
            margin-bottom: 8px;
            font-size: 24px;
          }
          
          .demo-section p {
            color: #666;
            margin-bottom: 20px;
            font-size: 16px;
          }
          
          .demo-showcase {
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border: 2px dashed #e0e0e0;
          }
          
          .demo-status {
            background: #f0f8ff;
            padding: 20px;
            border-radius: 8px;
            border-left: 4px solid #4ECDC4;
          }
          
          .demo-status h3 {
            margin-top: 0;
            color: #333;
          }
          
          .status-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-top: 16px;
          }
          
          .status-item {
            padding: 12px;
            background: white;
            border-radius: 6px;
            border: 1px solid #e0e0e0;
          }
          
          .status-item strong {
            color: #555;
          }
          
          @media (max-width: 768px) {
            .collaboration-demo {
              padding: 16px;
            }
            
            .demo-section {
              padding: 16px;
            }
            
            .collaboration-demo__content h1 {
              font-size: 24px;
            }
            
            .demo-section h2 {
              font-size: 20px;
            }
          }
        `}</style>
      </div>
    </CollaborationProvider>
  );
};