import React, { useCallback, useState } from 'react';
import PropTypes from 'prop-types';
import { toast } from 'react-toastify';
import { formatTimestamp } from '../../../utils/formatTimestamp';
import { formatFileSize } from '../../../services/attachmentValidation';
import { getMusicNotationUrl } from '../../../helpers/rest';

/**
 * Get initials for avatar from sender name
 * Returns first letter of first and last name, or just first letter if single name
 * @param {string} name - Sender name
 * @returns {string} Initials (e.g., "JD" for "John Doe")
 */
const getInitials = name => {
  if (!name) return '?';
  const parts = name.trim().split(' ');
  if (parts.length === 1) return parts[0][0].toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
};

/**
 * Check if message is an attachment
 * @param {Object} message - Message object
 * @returns {boolean} True if message has attachment
 */
const isAttachmentMessage = message => {
  return message.attachmentId && message.attachmentName;
};

/**
 * JKChatMessage - Individual message display component
 *
 * Displays a single chat message with avatar, sender name, message text, and timestamp.
 * Supports attachment messages with distinct styling and metadata display.
 *
 * Features:
 * - Avatar with initials (first + last name)
 * - Sender name in bold
 * - Relative timestamp (via formatTimestamp utility)
 * - Message text with word wrapping
 * - Attachment display with paperclip icon, filename, and size
 * - React.memo for performance optimization
 */
const JKChatMessage = ({ message }) => {
  const { senderName, message: text, createdAt, attachmentId, attachmentName, attachmentSize } = message;
  const [isLoadingUrl, setIsLoadingUrl] = useState(false);

  /**
   * Handle attachment click - fetch signed S3 URL and open in new tab
   * @param {string} attachmentId - ID of the attachment to open
   */
  const handleAttachmentClick = useCallback(
    async attachmentId => {
      if (isLoadingUrl) return; // Prevent rapid clicks

      try {
        setIsLoadingUrl(true);
        const response = await getMusicNotationUrl(attachmentId);
        // Response is { url: "https://s3.amazonaws.com/...?signature=..." }
        if (response && response.url) {
          window.open(response.url, '_blank');
        } else {
          console.error('No URL in response:', response);
        }
      } catch (error) {
        console.error('Failed to fetch attachment URL:', error);
        // Show user-friendly error (REQ-5.5)
        toast.error('File no longer available');
      } finally {
        setIsLoadingUrl(false);
      }
    },
    [isLoadingUrl]
  );

  // Common avatar style
  const avatarStyle = {
    width: '36px',
    height: '36px',
    borderRadius: '50%',
    backgroundColor: '#007bff',
    color: 'white',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    fontWeight: 'bold',
    fontSize: '14px',
    flexShrink: 0
  };

  // Attachment message styling
  if (isAttachmentMessage(message)) {
    const attachmentStyle = {
      display: 'flex',
      gap: '12px',
      marginBottom: '16px',
      padding: '8px',
      borderRadius: '4px',
      backgroundColor: '#e3f2fd',
      border: '1px solid #bbdefb'
    };

    const fileIconStyle = {
      fontSize: '16px',
      flexShrink: 0
    };

    return (
      <div style={attachmentStyle}>
        {/* Avatar */}
        <div style={avatarStyle}>{getInitials(senderName)}</div>

        {/* Attachment content */}
        <div style={{ flex: 1, minWidth: 0 }}>
          {/* Header: Name + Timestamp */}
          <div style={{ display: 'flex', alignItems: 'baseline', gap: '8px', marginBottom: '4px', flexWrap: 'wrap' }}>
            <span style={{ fontWeight: 600, fontSize: '14px', color: '#212529' }}>{senderName || 'Unknown'}</span>
            <span style={{ fontSize: '12px', color: '#6c757d' }}>{formatTimestamp(createdAt)}</span>
          </div>
          <div
            style={{
              fontSize: '14px',
              color: '#212529',
              display: 'flex',
              alignItems: 'center',
              flexWrap: 'wrap',
              gap: '4px'
            }}
          >
            <span style={fileIconStyle} role="img" aria-label="attachment">
              📎
            </span>
            <span>attached</span>
            <span
              onClick={() => handleAttachmentClick(attachmentId)}
              style={{
                cursor: isLoadingUrl ? 'wait' : 'pointer',
                color: '#1976d2',
                textDecoration: 'underline',
                fontWeight: 600,
                maxWidth: '100%',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                display: 'inline-block',
                verticalAlign: 'bottom'
              }}
              title={attachmentName}
            >
              {attachmentName}
            </span>
            {attachmentSize && (
              <span style={{ color: '#6c757d', fontSize: '13px', flexShrink: 0 }}>
                ({formatFileSize(attachmentSize)})
              </span>
            )}
          </div>
        </div>
      </div>
    );
  }

  // Regular text message
  return (
    <div
      style={{
        display: 'flex',
        gap: '12px',
        marginBottom: '16px',
        padding: '8px',
        borderRadius: '4px',
        backgroundColor: '#f8f9fa'
      }}
    >
      {/* Avatar */}
      <div style={avatarStyle}>{getInitials(senderName)}</div>

      {/* Message content */}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: '8px', marginBottom: '4px' }}>
          <span style={{ fontWeight: 600, fontSize: '14px', color: '#212529' }}>{senderName || 'Unknown'}</span>
          <span style={{ fontSize: '12px', color: '#6c757d' }}>{formatTimestamp(createdAt)}</span>
        </div>
        <div style={{ fontSize: '14px', color: '#212529', wordWrap: 'break-word' }}>{text}</div>
      </div>
    </div>
  );
};

JKChatMessage.propTypes = {
  message: PropTypes.shape({
    id: PropTypes.string.isRequired,
    senderId: PropTypes.string.isRequired,
    senderName: PropTypes.string,
    message: PropTypes.string, // Optional for attachment-only messages
    createdAt: PropTypes.string.isRequired,
    // Attachment fields (optional)
    attachmentId: PropTypes.string,
    attachmentName: PropTypes.string,
    attachmentType: PropTypes.oneOf(['notation', 'audio']),
    purpose: PropTypes.string,
    attachmentSize: PropTypes.number
  }).isRequired
};

export default React.memo(JKChatMessage);
