import React, { useState } from 'react'
import { Message } from '../../types'
import { downloadFile, getFileIcon, formatFileSize, refreshMediaUrl } from '../../utils/messageUtils'
import { logger } from '../../utils/logger'
import { api } from '../../services/api'
import { normalizeExternalUrl } from '../../utils/urlUtils'
import { isNotificationLikeMessage } from '../../utils/messageTypes'
import { formatApiMessageToMessage } from '../../utils/formatMessage'
import { showToast } from '../../utils/toast'

const OPEN_IN_SYSTEM_BROWSER_KEY = 'launchpad-open-in-system-browser'

interface MessageBubbleProps {
  msg: Message
  uploadProgress?: { [key: string]: number }
  activeContactId: number | null
  currentUserId: number | null
  token: string
  setMessages: React.Dispatch<React.SetStateAction<Record<number, Message[]>>>
}

export const MessageBubble: React.FC<MessageBubbleProps> = ({
  msg,
  uploadProgress = {},
  activeContactId,
  currentUserId,
  token,
  setMessages
}) => {
  const [actionLoading, setActionLoading] = useState(false)
  const [remindLoading, setRemindLoading] = useState(false)

  // 通知类型消息（带跳转：先请求 callback-url 再打开，打开方式与应用中心一致）
  if (msg.type === 'notification' || isNotificationLikeMessage(msg.messageType, msg.content_type)) {
    const openInSystemBrowser = (() => {
      try {
        return localStorage.getItem(OPEN_IN_SYSTEM_BROWSER_KEY) === 'true'
      } catch {
        return false
      }
    })()

    const isSenderUserNotification =
      msg.isSelf && msg.content_type === 'USER_NOTIFICATION'
    const targetReceiverId = msg.receiver_id ?? activeContactId
    const showRemindButton = Boolean(isSenderUserNotification && targetReceiverId != null)
    const showCallbackButton = Boolean(!isSenderUserNotification && msg.actionUrl)

    const handleRemind = async (e: React.MouseEvent) => {
      e.stopPropagation()
      const rid = msg.receiver_id ?? activeContactId
      if (!rid || remindLoading) return
      setRemindLoading(true)
      try {
        const response = await api.sendUserNotificationMessage(token, {
          receiverId: rid,
          title: msg.title || '通知',
          content: msg.content || '',
          actionUrl: msg.actionUrl,
          actionText: msg.actionText,
          appId: msg.app_id
        })
        const newMsg = formatApiMessageToMessage(response, currentUserId)
        if (activeContactId == null) return
        setMessages(prev => {
          const list = prev[activeContactId] || []
          if (list.some(m => m.id === newMsg.id)) return prev
          return {
            ...prev,
            [activeContactId]: [...list, newMsg]
          }
        })
      } catch (err) {
        logger.error('MessageBubble: remind failed', err)
        showToast(err instanceof Error ? err.message : '发送失败')
      } finally {
        setRemindLoading(false)
      }
    }

    const handleNotificationAction = async (e: React.MouseEvent) => {
      if (!msg.actionUrl) return
      e.stopPropagation()
      setActionLoading(true)
      try {
        let urlToOpen: string
        try {
          const res = await api.getMessageCallbackUrl(token, msg.id)
          urlToOpen = res.callback_url
        } catch (err) {
          logger.warn('MessageBubble: callback-url failed, fallback to actionUrl', err)
          urlToOpen = msg.actionUrl ?? ''
        }
        const normalized = normalizeExternalUrl(urlToOpen)
        if (!normalized) {
          logger.warn('MessageBubble: invalid URL for open', { urlToOpen })
          return
        }
        if (openInSystemBrowser && window.electron?.ipcRenderer) {
          window.electron.ipcRenderer.send('open-url-external', normalized)
        } else {
          window.open(normalized, '_blank')
        }
      } finally {
        setActionLoading(false)
      }
    }

    return (
      <div
        style={{
          width: '100%',
          boxSizing: 'border-box',
          minWidth: 0,
          border: '1px solid #e0e0e0',
          borderRadius: '8px',
          overflow: 'hidden',
          backgroundColor: '#fff'
        }}
      >
        {msg.title && (
          <div
            style={{
              fontSize: '15px',
              fontWeight: 600,
              color: '#2e7d32',
              backgroundColor: '#e8f5e9',
              padding: '10px 12px',
              lineHeight: 1.4
            }}
          >
            {msg.title}
          </div>
        )}
        <div
          style={{
            fontSize: '14px',
            color: '#333',
            padding: '12px',
            whiteSpace: 'pre-wrap',
            wordBreak: 'break-word',
            backgroundColor: '#ffffff'
          }}
        >
          {msg.content}
        </div>
        {(showRemindButton || showCallbackButton) && (
          <div style={{ padding: '0 12px 12px', backgroundColor: '#ffffff' }}>
            {showRemindButton && (
              <button
                type="button"
                onClick={(e) => handleRemind(e)}
                disabled={remindLoading}
                style={{
                  padding: '5px 16px',
                  backgroundColor: 'transparent',
                  color: remindLoading ? '#999' : '#1890ff',
                  border: `1px solid ${remindLoading ? '#d9d9d9' : '#1890ff'}`,
                  borderRadius: '4px',
                  cursor: remindLoading ? 'not-allowed' : 'pointer',
                  fontSize: '13px',
                  fontWeight: 500,
                  transition: 'color 0.2s, border-color 0.2s, background-color 0.2s'
                }}
                onMouseEnter={(e) => {
                  if (remindLoading) return
                  e.currentTarget.style.backgroundColor = 'rgba(24, 144, 255, 0.06)'
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.backgroundColor = 'transparent'
                }}
              >
                {remindLoading ? '发送中...' : '再次提醒'}
              </button>
            )}
            {showCallbackButton && (
              <button
                type="button"
                onClick={(e) => handleNotificationAction(e)}
                disabled={actionLoading}
                style={{
                  padding: '5px 16px',
                  backgroundColor: 'transparent',
                  color: actionLoading ? '#999' : '#1890ff',
                  border: `1px solid ${actionLoading ? '#d9d9d9' : '#1890ff'}`,
                  borderRadius: '4px',
                  cursor: actionLoading ? 'not-allowed' : 'pointer',
                  fontSize: '13px',
                  fontWeight: 500,
                  transition: 'color 0.2s, border-color 0.2s, background-color 0.2s'
                }}
                onMouseEnter={(e) => {
                  if (actionLoading) return
                  e.currentTarget.style.backgroundColor = 'rgba(24, 144, 255, 0.06)'
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.backgroundColor = 'transparent'
                }}
              >
                {actionLoading ? '跳转中...' : (msg.actionText || '立即处理')}
              </button>
            )}
          </div>
        )}
      </div>
    )
  }

  // 图片消息
  if (msg.type === 'image' || msg.content_type === 'IMAGE') {
    const fileId = `${msg.id}-${msg.timestamp}`;
    const progress = uploadProgress[fileId];
    
    return (
      <div style={{ position: 'relative' }}>
        <img 
          src={msg.content} 
          alt={msg.title || '图片'}
          style={{ 
            maxWidth: '150px', 
            maxHeight: '150px',
            borderRadius: '4px',
            cursor: 'pointer',
            objectFit: 'cover'
          }}
          onClick={() => {
            if (window.electron && window.electron.ipcRenderer) {
              window.electron.ipcRenderer.send('open-image-preview', msg.content)
            }
          }}
          onError={async () => {
            logger.warn('Image load failed, may be expired', { content: msg.content });
            await refreshMediaUrl(msg, activeContactId, token, setMessages);
          }}
        />
        {progress !== undefined && (
          <div style={{
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: 'rgba(0,0,0,0.5)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'white',
            borderRadius: '4px'
          }}>
            上传中 {progress}%
          </div>
        )}
      </div>
    );
  }

  // 视频消息
  if (msg.type === 'video' || msg.content_type === 'VIDEO') {
    return (
      <div style={{ position: 'relative', maxWidth: '150px' }}>
        <div style={{ 
          position: 'relative', 
          width: '100%', 
          height: '150px', 
          borderRadius: '4px', 
          overflow: 'hidden', 
          backgroundColor: '#000' 
        }}>
          <video 
            src={msg.content}
            preload="auto"
            muted
            playsInline
            style={{
              width: '100%',
              height: '100%',
              objectFit: 'cover',
              display: 'block'
            }}
            onLoadedMetadata={(e) => {
              const video = e.currentTarget;
              if (video.duration > 0) {
                video.currentTime = 0.5;
              }
            }}
            onLoadedData={(e) => {
              e.currentTarget.pause();
            }}
            onSeeked={(e) => {
              e.currentTarget.pause();
            }}
            onCanPlay={(e) => {
              e.currentTarget.pause();
            }}
            onError={async () => {
              logger.warn('Video load failed, may be expired', { content: msg.content });
              await refreshMediaUrl(msg, activeContactId, token, setMessages);
            }}
          />
          <div
            onClick={(e) => {
              e.stopPropagation();
              if (window.electron && window.electron.ipcRenderer) {
                window.electron.ipcRenderer.send('open-video-player', msg.content, msg.title || 'video.mp4');
              }
            }}
            style={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              width: '40px',
              height: '40px',
              borderRadius: '50%',
              backgroundColor: 'rgba(0, 0, 0, 0.6)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              cursor: 'pointer',
              transition: 'all 0.3s ease',
              zIndex: 10
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
              e.currentTarget.style.transform = 'translate(-50%, -50%) scale(1.1)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.6)';
              e.currentTarget.style.transform = 'translate(-50%, -50%) scale(1)';
            }}
          >
            <div
              style={{
                width: 0,
                height: 0,
                borderLeft: '14px solid white',
                borderTop: '8px solid transparent',
                borderBottom: '8px solid transparent',
                marginLeft: '3px'
              }}
            />
          </div>
        </div>
      </div>
    );
  }

  // 文件消息
  if (msg.type === 'file' || msg.content_type === 'FILE') {
    return (
      <div 
        style={{ 
          display: 'flex', 
          alignItems: 'center', 
          minWidth: '200px',
          maxWidth: '300px',
          padding: '8px',
          backgroundColor: '#f5f5f5',
          borderRadius: '4px',
          cursor: 'pointer'
        }}
        onClick={(e) => {
          e.stopPropagation();
          downloadFile(msg.content, msg.title || 'file');
        }}
      >
        <div style={{ fontSize: '30px', marginRight: '10px' }}>
          {getFileIcon(msg.title || 'file')}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ 
            fontSize: '14px', 
            fontWeight: '500',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap'
          }}>
            {msg.title || '文件'}
          </div>
          <div style={{ fontSize: '12px', color: '#888', marginTop: '4px' }}>
            {formatFileSize(msg.size)}
          </div>
        </div>
        <div style={{ fontSize: '20px', marginLeft: '8px' }}>⬇️</div>
      </div>
    );
  }

  // 文本消息（支持链接）
  const urlRegex = /(https?:\/\/[^\s]+)/g
  const parts = msg.content.split(urlRegex)
  
  return (
    <div style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
      {parts.map((part, index) => {
        if (part.match(urlRegex)) {
          return (
            <a
              key={index}
              href={part}
              target="_blank"
              rel="noopener noreferrer"
              style={{ color: '#0066cc', textDecoration: 'underline', cursor: 'pointer' }}
              onClick={(e) => e.stopPropagation()}
            >
              {part}
            </a>
          )
        }
        return part
      })}
    </div>
  )
}
