import React, { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Button } from 'reactstrap';
import {
  openChatWindow,
  setActiveChannel,
  selectTotalUnreadCount,
  selectIsChatWindowOpen
} from '../../store/features/sessionChatSlice';
import chatIcon from '../../assets/img/client/chat.svg';

const JKSessionChatButton = ({ sessionId }) => {
  const dispatch = useDispatch();
  const unreadCount = useSelector(selectTotalUnreadCount);
  const isWindowOpen = useSelector(selectIsChatWindowOpen);

  const handleClick = useCallback(() => {
    if (isWindowOpen) {
      // Window already open - do nothing (or focus window if possible)
      return;
    }

    // Set active channel to session chat
    dispatch(setActiveChannel({
      channel: sessionId,
      channelType: 'session'
    }));

    // Open chat window
    dispatch(openChatWindow());
  }, [dispatch, sessionId, isWindowOpen]);

  // Format badge text
  const getBadgeText = () => {
    if (unreadCount === 0) return '';
    if (unreadCount >= 100) return '99+';
    return String(unreadCount);
  };

  return (
    <div style={{ position: 'relative', display: 'inline-block' }}>
      <Button
        className='btn-custom-outline'
        outline
        size="md"
        onClick={handleClick}
        aria-label={`Open chat${unreadCount > 0 ? ` (${unreadCount} unread)` : ''}`}
        aria-pressed={isWindowOpen}
        title="Open session chat"
        style={{ opacity: isWindowOpen ? 0.6 : 1 }}
      >
        <img
          src={chatIcon}
          alt="Chat"
          style={{ width: '20px', height: '20px', marginRight: '0.3rem' }}
        />
        Chat
      </Button>
      {unreadCount > 0 && (
        <div
          style={{
            position: 'absolute',
            top: '1px',
            right: '-5px',
            backgroundColor: '#dc3545',
            color: 'white',
            borderRadius: '10px',
            padding: '2px 6px',
            fontSize: '11px',
            fontWeight: 'bold',
            lineHeight: '1',
            minWidth: '18px',
            textAlign: 'center',
            boxShadow: '0 1px 3px rgba(0,0,0,0.3)',
            zIndex: 1
          }}
        >
          {getBadgeText()}
        </div>
      )}
    </div>
  );
};

export default JKSessionChatButton;
