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

interface TaskData {
  id: string;
  title: string;
  description: string;
  status: string;
  priority: string;
  assignees: string[];
  tags: string[];
}

interface CollaborativeTaskFormProps {
  taskId: string;
  initialData?: Partial<TaskData>;
  onSave?: (data: TaskData) => void;
  className?: string;
}

/**
 * Collaborative Task Form
 * A form component that supports real-time collaboration
 */
export const CollaborativeTaskForm: React.FC<CollaborativeTaskFormProps> = ({
  taskId,
  initialData = {},
  onSave,
  className = ''
}) => {
  const collaboration = useCollaborationContext();
  const [localData, setLocalData] = useState<Partial<TaskData>>(initialData);
  const [awareness, setAwareness] = useState<any[]>([]);

  // Update local data when collaboration values change
  useEffect(() => {
    const updateFromCollaboration = () => {
      const title = collaboration.getValue('title') || '';
      const description = collaboration.getValue('description') || '';
      const status = collaboration.getValue('status') || 'pending';
      const priority = collaboration.getValue('priority') || 'medium';
      const assignees = collaboration.getValue('assignees') || [];
      const tags = collaboration.getValue('tags') || [];

      setLocalData({
        id: taskId,
        title,
        description,
        status,
        priority,
        assignees,
        tags
      });
    };

    // Update on mount and when collaboration data changes
    updateFromCollaboration();
    
    // Set up interval to sync data periodically
    const interval = setInterval(updateFromCollaboration, 1000);
    
    return () => clearInterval(interval);
  }, [collaboration, taskId]);

  // Handle field changes
  const handleFieldChange = (field: string, value: any) => {
    // Update collaboration
    collaboration.updateField(field, value);
    
    // Update local state immediately for responsiveness
    setLocalData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  // Handle cursor changes
  const handleCursorChange = (field: string, position: number, selection?: { start: number; end: number }) => {
    collaboration.updateCursor(field, position, selection);
  };

  // Generate cursor positions for collaborative fields
  const getCursorPositions = (field: string) => {
    return collaboration.activeUsers
      .filter(user => user.cursor?.field === field)
      .map(user => ({
        userId: user.id,
        field: user.cursor!.field,
        position: user.cursor!.position,
        selection: user.cursor!.selection,
        color: user.color,
        userName: user.name
      }));
  };

  // Handle save
  const handleSave = () => {
    if (onSave && localData.id) {
      onSave(localData as TaskData);
    }
  };

  // Create section awareness
  const createSectionAwareness = (section: string) => {
    // This would be populated from the collaboration service
    // For now, we'll use mock data
    return awareness.filter(a => a.section === section);
  };

  return (
    <div className={`collaborative-task-form ${className}`}>
      <div className="collaborative-task-form__header">
        <h2 className="collaborative-task-form__title">
          {localData.title || 'Untitled Task'}
        </h2>
        
        <div className="collaborative-task-form__presence">
          <UserPresence
            users={collaboration.activeUsers}
            maxDisplay={5}
            showCursors={true}
          />
        </div>
      </div>

      <form className="collaborative-task-form__form" onSubmit={(e) => { e.preventDefault(); handleSave(); }}>
        <div className="collaborative-task-form__section" data-section="basic-info">
          <AwarenessIndicator
            section="basic-info"
            awareness={createSectionAwareness('basic-info')}
            currentUserId={collaboration.state.localUser.id}
            position="right"
          />
          
          <div className="collaborative-task-form__field">
            <label htmlFor="title">Title</label>
            <CollaborativeField
              fieldName="title"
              value={localData.title || ''}
              onChange={(value) => handleFieldChange('title', value)}
              onCursorChange={(pos, sel) => handleCursorChange('title', pos, sel)}
              cursors={getCursorPositions('title')}
              placeholder="Enter task title..."
              className="collaborative-task-form__input"
            />
          </div>

          <div className="collaborative-task-form__field">
            <label htmlFor="description">Description</label>
            <CollaborativeField
              fieldName="description"
              value={localData.description || ''}
              onChange={(value) => handleFieldChange('description', value)}
              onCursorChange={(pos, sel) => handleCursorChange('description', pos, sel)}
              cursors={getCursorPositions('description')}
              placeholder="Enter task description..."
              multiline={true}
              className="collaborative-task-form__textarea"
            />
          </div>
        </div>

        <div className="collaborative-task-form__section" data-section="metadata">
          <AwarenessIndicator
            section="metadata"
            awareness={createSectionAwareness('metadata')}
            currentUserId={collaboration.state.localUser.id}
            position="right"
          />
          
          <div className="collaborative-task-form__row">
            <div className="collaborative-task-form__field">
              <label htmlFor="status">Status</label>
              <select
                value={localData.status || 'pending'}
                onChange={(e) => handleFieldChange('status', e.target.value)}
                className="collaborative-task-form__select"
              >
                <option value="pending">Pending</option>
                <option value="in-progress">In Progress</option>
                <option value="review">Review</option>
                <option value="done">Done</option>
                <option value="cancelled">Cancelled</option>
              </select>
            </div>

            <div className="collaborative-task-form__field">
              <label htmlFor="priority">Priority</label>
              <select
                value={localData.priority || 'medium'}
                onChange={(e) => handleFieldChange('priority', e.target.value)}
                className="collaborative-task-form__select"
              >
                <option value="low">Low</option>
                <option value="medium">Medium</option>
                <option value="high">High</option>
                <option value="urgent">Urgent</option>
              </select>
            </div>
          </div>
        </div>

        <div className="collaborative-task-form__actions">
          <button 
            type="submit" 
            className="collaborative-task-form__save"
            disabled={!collaboration.isConnected}
          >
            Save Task
          </button>
          
          {collaboration.hasUnsavedChanges && (
            <span className="collaborative-task-form__unsaved">
              Unsaved changes
            </span>
          )}
          
          <div className="collaborative-task-form__status">
            {collaboration.isConnected ? (
              <span className="collaborative-task-form__connected">🟢 Connected</span>
            ) : (
              <span className="collaborative-task-form__disconnected">🔴 Disconnected</span>
            )}
          </div>
        </div>
      </form>
      
      <style jsx>{`
        .collaborative-task-form {
          background: white;
          padding: 24px;
          border-radius: 12px;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          max-width: 800px;
          margin: 0 auto;
        }
        
        .collaborative-task-form__header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 24px;
          padding-bottom: 16px;
          border-bottom: 1px solid #e0e0e0;
        }
        
        .collaborative-task-form__title {
          margin: 0;
          color: #333;
          font-size: 24px;
          font-weight: 600;
        }
        
        .collaborative-task-form__presence {
          flex-shrink: 0;
        }
        
        .collaborative-task-form__form {
          display: flex;
          flex-direction: column;
          gap: 24px;
        }
        
        .collaborative-task-form__section {
          position: relative;
          padding: 16px;
          border: 1px solid #f0f0f0;
          border-radius: 8px;
          background: #fafafa;
        }
        
        .collaborative-task-form__field {
          margin-bottom: 16px;
        }
        
        .collaborative-task-form__field:last-child {
          margin-bottom: 0;
        }
        
        .collaborative-task-form__field label {
          display: block;
          margin-bottom: 6px;
          font-weight: 500;
          color: #555;
          font-size: 14px;
        }
        
        .collaborative-task-form__input,
        .collaborative-task-form__textarea,
        .collaborative-task-form__select {
          width: 100%;
          padding: 10px 12px;
          border: 1px solid #ddd;
          border-radius: 6px;
          font-size: 14px;
          background: white;
          transition: border-color 0.2s ease, box-shadow 0.2s ease;
        }
        
        .collaborative-task-form__input:focus,
        .collaborative-task-form__textarea:focus,
        .collaborative-task-form__select:focus {
          outline: none;
          border-color: #4ECDC4;
          box-shadow: 0 0 0 3px rgba(78, 205, 196, 0.1);
        }
        
        .collaborative-task-form__textarea {
          min-height: 120px;
          resize: vertical;
          font-family: inherit;
        }
        
        .collaborative-task-form__row {
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 16px;
        }
        
        .collaborative-task-form__actions {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding-top: 16px;
          border-top: 1px solid #e0e0e0;
        }
        
        .collaborative-task-form__save {
          background: #4ECDC4;
          color: white;
          border: none;
          padding: 12px 24px;
          border-radius: 6px;
          font-size: 14px;
          font-weight: 500;
          cursor: pointer;
          transition: background 0.2s ease;
        }
        
        .collaborative-task-form__save:hover:not(:disabled) {
          background: #45B7D1;
        }
        
        .collaborative-task-form__save:disabled {
          background: #ccc;
          cursor: not-allowed;
        }
        
        .collaborative-task-form__unsaved {
          color: #ff9800;
          font-size: 13px;
          font-style: italic;
        }
        
        .collaborative-task-form__status {
          font-size: 13px;
        }
        
        .collaborative-task-form__connected {
          color: #4caf50;
        }
        
        .collaborative-task-form__disconnected {
          color: #f44336;
        }
        
        @media (max-width: 600px) {
          .collaborative-task-form {
            padding: 16px;
          }
          
          .collaborative-task-form__header {
            flex-direction: column;
            gap: 12px;
            align-items: flex-start;
          }
          
          .collaborative-task-form__row {
            grid-template-columns: 1fr;
          }
          
          .collaborative-task-form__actions {
            flex-direction: column;
            gap: 12px;
            align-items: stretch;
          }
        }
      `}</style>
    </div>
  );
};