/**
 * Collaborator List Component
 * Displays list of active collaborators with their editing context
 */

import { Component, createEffect, onMount, createSignal } from 'solid-js';
import { RemoteUser } from '../../lib/collaboration/presence';

export interface CollaboratorListProps {
  getRemoteUsers: () => Map<string, RemoteUser>;
  onVideoCallInitiate?: (userId: string) => void;
  className?: string;
}

export const CollaboratorList: Component<CollaboratorListProps> = (props) => {
  const [users, setUsers] = createSignal<RemoteUser[]>([]);
  const [isOpen, setIsOpen] = createSignal(true);

  onMount(() => {
    const updateUsers = () => {
      const userMap = props.getRemoteUsers();
      setUsers(Array.from(userMap.values()));
    };

    updateUsers();

    // Poll for updates (in production, use subscription pattern)
    const interval = setInterval(updateUsers, 1000);

    return () => {
      clearInterval(interval);
    };
  });

  const getStatusIndicatorColor = (user: RemoteUser): string => {
    if (user.isEditing) {
      return '#22c55e'; // green - actively editing
    }
    return '#94a3b8'; // gray - idle
  };

  const getElapsedTime = (lastActive: Date): string => {
    const now = new Date();
    const diff = now.getTime() - new Date(lastActive).getTime();
    
    if (diff < 60000) {
      return 'Just now';
    } else if (diff < 3600000) {
      const minutes = Math.floor(diff / 60000);
      return `${minutes}m ago`;
    } else {
      const hours = Math.floor(diff / 3600000);
      return `${hours}h ago`;
    }
  };

  return (
    <div
      class={props.className || 'collaborator-list'}
      style={{
        width: '280px',
        maxHeight: '400px',
        overflow: 'auto',
        backgroundColor: '#fff',
        border: '1px solid #e2e8f0',
        borderRadius: '8px',
        boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
      }}
    >
      <div
        onClick={() => setIsOpen(!isOpen())}
        style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '12px 16px',
          borderBottom: '1px solid #e2e8f0',
          cursor: 'pointer',
          userSelect: 'none',
        }}
      >
        <span style={{ fontWeight: '600', fontSize: '14px' }}>
          Collaborators ({users().length})
        </span>
        <span style={{ fontSize: '12px', color: '#64748b' }}>
          {isOpen() ? '▼' : '▶'}
        </span>
      </div>

      {isOpen() && (
        <div>
          {users().length === 0 ? (
            <div style={{ padding: '20px 16px', textAlign: 'center', color: '#94a3b8', fontSize: '13px' }}>
              No other collaborators
            </div>
          ) : (
            users().map((user) => (
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  padding: '10px 16px',
                  borderBottom: '1px solid #f1f5f9',
                  gap: '10px',
                }}
              >
                {/* Avatar */}
                <div
                  style={{
                    width: '36px',
                    height: '36px',
                    borderRadius: '50%',
                    backgroundColor: user.cursor?.color || '#cbd5e1',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: '14px',
                    fontWeight: '600',
                    color: '#fff',
                    position: 'relative',
                  }}
                >
                  {user.userName.charAt(0).toUpperCase()}
                  {/* Status indicator */}
                  <span
                    style={{
                      position: 'absolute',
                      bottom: '0',
                      right: '0',
                      width: '10px',
                      height: '10px',
                      borderRadius: '50%',
                      backgroundColor: getStatusIndicatorColor(user),
                      border: '2px solid #fff',
                    }}
                  />
                </div>

                {/* User info */}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div
                    style={{
                      fontWeight: '500',
                      fontSize: '13px',
                      color: '#1e293b',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                    }}
                  >
                    {user.userName}
                  </div>
                  <div
                    style={{
                      fontSize: '11px',
                      color: user.isEditing ? '#22c55e' : '#94a3b8',
                    }}
                  >
                    {user.isEditing ? 'Editing...' : `Idle (${getElapsedTime(user.lastActive)})`}
                  </div>
                  {user.cursor && (
                    <div style={{ fontSize: '11px', color: '#64748b', marginTop: '2px' }}>
                      Position: {user.cursor.position}
                    </div>
                  )}
                </div>

                {/* Video call button */}
                {props.onVideoCallInitiate && (
                  <button
                    onClick={() => props.onVideoCallInitiate!(user.userId)}
                    style={{
                      padding: '6px 10px',
                      backgroundColor: '#3b82f6',
                      color: '#fff',
                      border: 'none',
                      borderRadius: '4px',
                      fontSize: '11px',
                      cursor: 'pointer',
                      transition: 'background-color 0.2s',
                    }}
                    title="Start video call"
                  >
                    📹 Video
                  </button>
                )}
              </div>
            ))
          )}
        </div>
      )}
    </div>
  );
};

export default CollaboratorList;
