import React, { useCallback, useEffect, useRef } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import WindowPortal from '../common/WindowPortal.js';
import JKChatHeader from './chat/JKChatHeader.js';
import JKChatMessageList from './chat/JKChatMessageList.js';
import JKChatComposer from './chat/JKChatComposer.js';
import {
  selectIsChatWindowOpen,
  selectActiveChannel,
  closeChatWindow
} from '../../store/features/sessionChatSlice';
import { useJamServerContext } from '../../context/JamServerContext';

/**
 * JKSessionChatWindow - Main chat window component with WindowPortal integration
 *
 * Opens chat in a popup window (450×600px) following the WindowPortal pattern
 * established in Backing Track/JamTrack players.
 *
 * Redux Integration:
 * - isWindowOpen: Controls visibility
 * - activeChannel: Determines channel name
 * - closeChatWindow: Action to close window
 *
 * Component hierarchy:
 * WindowPortal → JKChatHeader + JKChatMessageList + JKChatComposer
 *
 * Layout:
 * - Header: Fixed at top (~50px)
 * - Message List: Scrollable, fills middle space
 * - Composer: Fixed at bottom (~120px)
 */
const JKSessionChatWindow = () => {
  const dispatch = useDispatch();
  const textareaRef = useRef(null);

  // Redux selectors
  const isWindowOpen = useSelector(selectIsChatWindowOpen);
  const activeChannel = useSelector(selectActiveChannel);

  // WebSocket connection status
  const { isConnected } = useJamServerContext();

  // Handlers
  const handleClose = useCallback(() => {
    dispatch(closeChatWindow());
  }, [dispatch]);

  // Channel name formatting
  const getChannelName = useCallback(() => {
    if (!activeChannel) return 'Session Chat';
    if (activeChannel === 'global') return 'Global Chat';
    // Session-specific channels will be formatted here
    // For now, default to 'Session Chat'
    return 'Session Chat';
  }, [activeChannel]);

  // Keyboard shortcut: Escape to close window
  useEffect(() => {
    const handleKeyDown = (e) => {
      if (e.key === 'Escape') {
        dispatch(closeChatWindow());
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [dispatch]);

  // Focus management: Auto-focus textarea when window opens
  useEffect(() => {
    if (isWindowOpen && textareaRef.current) {
      // Delay focus to ensure DOM is ready
      setTimeout(() => {
        if (textareaRef.current) {
          textareaRef.current.focus();
        }
      }, 100);
    }
  }, [isWindowOpen]);

  // Conditional render: only show if window is open
  if (!isWindowOpen) return null;

  return (
    <WindowPortal
      title="JamKazam Chat"
      windowFeatures="width=450,height=600,left=200,top=200,menubar=no,toolbar=no,status=no,scrollbars=no,resizable=yes"
      onClose={handleClose}
      windowId="jamkazam-chat"
    >
      <div
        role="dialog"
        aria-labelledby="chat-window-title"
        aria-modal="false"
        style={{ display: 'flex', flexDirection: 'column', height: '100%', width: '100%' }}
      >
        <JKChatHeader
          channelName={getChannelName()}
          onClose={handleClose}
        />
        {/* WebSocket disconnection banner */}
        {!isConnected && (
          <div
            style={{
              padding: '10px 16px',
              backgroundColor: '#fff3cd',
              color: '#856404',
              fontSize: '13px',
              borderBottom: '1px solid #ffeaa7',
              textAlign: 'center'
            }}
          >
            ⚠️ Connection lost. Reconnecting...
          </div>
        )}
        <div style={{ flex: 1, overflowY: 'auto' }}>
          <JKChatMessageList />
        </div>
        <JKChatComposer textareaRef={textareaRef} />
      </div>
    </WindowPortal>
  );
};

// No PropTypes needed - uses Redux internally
export default React.memo(JKSessionChatWindow);
