import React, { useState, useEffect } from 'react';
import './Overlay.css';

/**
 * In-game overlay component
 * Runs in iframe embedded in games via Nexus Engine
 */
export default function InGameOverlay() {
  const [minimized, setMinimized] = useState(false);
  const [activeTab, setActiveTab] = useState('friends');
  const [friends, setFriends] = useState([]);
  const [unreadMessages, setUnreadMessages] = useState(0);
  const [inCall, setInCall] = useState(false);
  const [socket, setSocket] = useState(null);

  useEffect(() => {
    initializeOverlay();
    loadFriends();
    setupWebSocket();

    // Listen for messages from game
    window.addEventListener('message', handleGameMessage);

    return () => {
      window.removeEventListener('message', handleGameMessage);
      if (socket) {
        socket.close();
      }
    };
  }, []);

  const initializeOverlay = () => {
    // Get session ID from URL params
    const params = new URLSearchParams(window.location.search);
    const sessionId = params.get('session');
    
    if (sessionId) {
      localStorage.setItem('overlay_session', sessionId);
    }
  };

  const setupWebSocket = () => {
    const token = localStorage.getItem('token');
    if (!token) return;

    const ws = new WebSocket(`ws://localhost:5000?token=${token}`);

    ws.onopen = () => {
      console.log('[Overlay] WebSocket connected');
    };

    ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      handleSocketMessage(data);
    };

    ws.onerror = (error) => {
      console.error('[Overlay] WebSocket error:', error);
    };

    ws.onclose = () => {
      console.log('[Overlay] WebSocket disconnected');
      // Reconnect after 3 seconds
      setTimeout(setupWebSocket, 3000);
    };

    setSocket(ws);
  };

  const loadFriends = async () => {
    try {
      const token = localStorage.getItem('token');
      if (!token) return;

      const response = await fetch('/api/friends', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      const data = await response.json();

      if (data.success) {
        setFriends(data.friends);
      }
    } catch (error) {
      console.error('[Overlay] Failed to load friends:', error);
    }
  };

  const handleSocketMessage = (data) => {
    switch (data.type) {
      case 'presence:updated':
        handlePresenceUpdate(data);
        break;
      case 'message:new':
        handleNewMessage(data);
        break;
      case 'friend:request':
        showNotification({
          icon: '👋',
          title: 'Friend Request',
          body: `${data.username} wants to be friends`
        });
        break;
      case 'friend:accepted':
        showNotification({
          icon: '✅',
          title: 'Friend Request Accepted',
          body: `${data.username} accepted your friend request`
        });
        loadFriends(); // Refresh friends list
        break;
    }
  };

  const handlePresenceUpdate = (data) => {
    setFriends(prev => prev.map(friend => 
      friend.userId === data.userId 
        ? { 
            ...friend, 
            status: data.status, 
            lastSeen: data.lastSeenAt,
            currentGame: data.currentGame
          }
        : friend
    ));
  };

  const handleNewMessage = (data) => {
    setUnreadMessages(prev => prev + 1);
    
    // Show notification
    showNotification({
      icon: '💬',
      title: 'New Message',
      body: `${data.senderDisplayName}: ${data.content.substring(0, 50)}${data.content.length > 50 ? '...' : ''}`
    });
  };

  const showNotification = (notification) => {
    // Notify parent window (game)
    if (window.parent !== window) {
      window.parent.postMessage({
        type: 'notification',
        data: notification
      }, '*');
    }

    // Also show in overlay if not minimized
    if (!minimized) {
      // Could add in-overlay toast here
    }
  };

  const handleGameMessage = (event) => {
    // Handle messages from game
    if (event.data.type === 'auto_mute') {
      if (event.data.mute && inCall) {
        console.log('[Overlay] Auto-muting for in-game match');
        // Auto-mute logic would trigger call service here
      } else {
        console.log('[Overlay] Auto-unmuting');
        // Auto-unmute logic
      }
    }
  };

  const toggleMinimize = () => {
    setMinimized(!minimized);
    
    // Notify parent
    if (window.parent !== window) {
      window.parent.postMessage({
        type: 'minimize',
        minimized: !minimized
      }, '*');
    }
  };

  const handleFriendClick = (friend) => {
    // Open quick actions menu for friend
    console.log('[Overlay] Friend clicked:', friend.username);
    // Could show: Send message, Join game, Voice call, etc.
  };

  if (minimized) {
    return (
      <div className="overlay-minimized" onClick={toggleMinimize}>
        <div className="minimized-icon">💬</div>
        {unreadMessages > 0 && (
          <div className="minimized-badge">{unreadMessages}</div>
        )}
      </div>
    );
  }

  return (
    <div className="in-game-overlay">
      <div className="overlay-header">
        <div className="overlay-tabs">
          <button 
            className={activeTab === 'friends' ? 'active' : ''}
            onClick={() => setActiveTab('friends')}
          >
            Friends ({friends.filter(f => f.status === 'online').length})
          </button>
          <button 
            className={activeTab === 'messages' ? 'active' : ''}
            onClick={() => setActiveTab('messages')}
          >
            Messages
            {unreadMessages > 0 && (
              <span className="badge">{unreadMessages}</span>
            )}
          </button>
        </div>
        <button className="btn-minimize" onClick={toggleMinimize}>
          —
        </button>
      </div>

      <div className="overlay-content">
        {activeTab === 'friends' && (
          <div className="friends-list">
            {friends.length === 0 ? (
              <div className="messages-preview">
                <p>No friends yet</p>
              </div>
            ) : (
              friends.map(friend => (
                <div 
                  key={friend.userId} 
                  className="friend-item"
                  onClick={() => handleFriendClick(friend)}
                >
                  <img 
                    src={friend.avatar || 'https://via.placeholder.com/40'} 
                    alt={friend.username} 
                  />
                  <div className="friend-info">
                    <div className="friend-name">{friend.username}</div>
                    {friend.currentGame && (
                      <div className="friend-game">
                        🎮 {friend.currentGame.gameName}
                      </div>
                    )}
                    {!friend.currentGame && friend.status === 'online' && (
                      <div className="friend-game">Online</div>
                    )}
                  </div>
                  <div className={`status-indicator ${friend.status || 'offline'}`} />
                </div>
              ))
            )}
          </div>
        )}

        {activeTab === 'messages' && (
          <div className="messages-preview">
            <p>Recent messages appear here</p>
            <p style={{ fontSize: '12px', marginTop: '8px', color: '#666' }}>
              Click a friend to start chatting
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
