import React, { useState } from 'react';
import { Check, CheckCheck, Download, Eye, Play, FileText, Image, Music } from 'lucide-react';
import { formatMessageTime } from '../../utils/dateFormatter';
import { formatFileSize } from '../../utils/fileValidation';
import { useAuth } from '../../contexts/AuthContext';

const MessageBubble = ({ message, isOwn, showAvatar, onRead }) => {
  const [imageError, setImageError] = useState(false);
  const [showImagePreview, setShowImagePreview] = useState(false);
  const { user } = useAuth();

  const handleDownload = (url, filename) => {
    // Create a temporary link to trigger download
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const getReadStatus = () => {
    if (!isOwn) return null;
    
    const readByCount = message.readBy?.length || 0;
    const participantCount = message.conversation?.participants?.length || 1;
    
    if (readByCount >= participantCount - 1) {
      return <CheckCheck className="w-4 h-4 text-blue-500" />;
    } else if (message.status === 'delivered') {
      return <CheckCheck className="w-4 h-4 text-gray-400" />;
    } else {
      return <Check className="w-4 h-4 text-gray-400" />;
    }
  };

  const renderAttachment = () => {
    if (!message.attachment) return null;

    const { url, originalName, mimeType, size, thumbnail } = message.attachment;

    // Image files
    if (mimeType.startsWith('image/')) {
      return (
        <div className="mt-2">
          <div className="relative group">
            <img
              src={imageError ? '/placeholder-image.jpg' : (thumbnail || url)}
              alt={originalName}
              className="max-w-xs rounded-lg cursor-pointer hover:opacity-90 transition-opacity border border-gray-200 dark:border-gray-600"
              onError={() => setImageError(true)}
              onClick={() => setShowImagePreview(true)}
            />
            <div className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity flex space-x-1">
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  handleDownload(url, originalName);
                }}
                className="bg-black bg-opacity-50 text-white p-1.5 rounded-lg hover:bg-opacity-70 transition-colors"
                title="Download"
              >
                <Download size={16} />
              </button>
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  setShowImagePreview(true);
                }}
                className="bg-black bg-opacity-50 text-white p-1.5 rounded-lg hover:bg-opacity-70 transition-colors"
                title="Preview"
              >
                <Eye size={16} />
              </button>
            </div>
          </div>
          <div className="flex justify-between items-center mt-2 text-sm">
            <span className="text-gray-600 dark:text-gray-400">{originalName}</span>
            <span className="text-gray-500 dark:text-gray-500">{formatFileSize(size)}</span>
          </div>
        </div>
      );
    }

    // Audio files
    if (mimeType.startsWith('audio/')) {
      return (
        <div className="mt-2">
          <div className="flex items-center space-x-3 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">
            <div className="flex-shrink-0">
              <Music className="w-8 h-8 text-primary-500" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-medium text-gray-900 dark:text-white truncate">
                {originalName}
              </p>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {formatFileSize(size)} • Audio
              </p>
            </div>
            <button
              onClick={() => handleDownload(url, originalName)}
              className="flex-shrink-0 p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors"
              title="Download"
            >
              <Download size={18} />
            </button>
          </div>
        </div>
      );
    }

    // Document files (PDF, TXT)
    return (
      <div className="mt-2">
        <div className="flex items-center space-x-3 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">
          <div className="flex-shrink-0">
            <FileText className="w-8 h-8 text-primary-500" />
          </div>
          <div className="flex-1 min-w-0">
            <p className="text-sm font-medium text-gray-900 dark:text-white truncate">
              {originalName}
            </p>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {formatFileSize(size)} • {mimeType.split('/')[1].toUpperCase()}
            </p>
          </div>
          <button
            onClick={() => handleDownload(url, originalName)}
            className="flex-shrink-0 p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-600 rounded-lg transition-colors"
            title="Download"
          >
            <Download size={18} />
          </button>
        </div>
      </div>
    );
  };

  // Image Preview Modal
  if (showImagePreview && message.attachment) {
    return (
      <>
        <div className={`flex ${isOwn ? 'justify-end' : 'justify-start'} mb-4`}>
          <div className={`max-w-xs lg:max-w-md px-4 py-2 rounded-2xl ${
            isOwn 
              ? 'bg-primary-500 text-white rounded-br-none' 
              : 'bg-gray-200 dark:bg-gray-700 text-gray-900 dark:text-white rounded-bl-none'
          }`}>
            {message.content && <p className="whitespace-pre-wrap">{message.content}</p>}
            {renderAttachment()}
            <div className={`flex items-center justify-between text-xs mt-1 ${isOwn ? 'text-primary-100' : 'text-gray-500'}`}>
              <span>{formatMessageTime(message.createdAt)}</span>
              {getReadStatus()}
            </div>
          </div>
        </div>

        {/* Image Preview Overlay */}
        <div 
          className="fixed inset-0 bg-black bg-opacity-90 z-50 flex items-center justify-center p-4"
          onClick={() => setShowImagePreview(false)}
        >
          <div 
            className="relative max-w-4xl max-h-full"
            onClick={(e) => e.stopPropagation()}
          >
            <img
              src={message.attachment.url}
              alt={message.attachment.originalName}
              className="max-w-full max-h-full object-contain rounded-lg"
            />
            <div className="absolute top-4 right-4 flex space-x-2">
              <button
                onClick={() => handleDownload(message.attachment.url, message.attachment.originalName)}
                className="bg-white bg-opacity-20 text-white p-3 rounded-lg hover:bg-opacity-30 transition-colors backdrop-blur-sm"
                title="Download"
              >
                <Download size={20} />
              </button>
              <button
                onClick={() => setShowImagePreview(false)}
                className="bg-white bg-opacity-20 text-white p-3 rounded-lg hover:bg-opacity-30 transition-colors backdrop-blur-sm"
                title="Close"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            <div className="absolute bottom-4 left-4 right-4 bg-black bg-opacity-50 text-white p-3 rounded-lg backdrop-blur-sm">
              <p className="text-sm truncate">{message.attachment.originalName}</p>
              <p className="text-xs text-gray-300">{formatFileSize(message.attachment.size)}</p>
            </div>
          </div>
        </div>
      </>
    );
  }

  return (
    <div className={`flex ${isOwn ? 'justify-end' : 'justify-start'} mb-4`}>
      {!isOwn && showAvatar && (
        <div className="flex-shrink-0 mr-2 self-end">
          <div className="w-8 h-8 bg-gradient-to-br from-primary-400 to-primary-600 rounded-full flex items-center justify-center text-white text-xs font-medium">
            {message.sender?.displayName?.charAt(0).toUpperCase() || 'U'}
          </div>
        </div>
      )}
      
      <div className={`max-w-xs lg:max-w-md px-4 py-2 rounded-2xl ${
        isOwn 
          ? 'message-bubble-own' 
          : 'message-bubble-other'
      }`}>
        {!isOwn && (
          <div className="text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">
            {message.sender?.displayName}
          </div>
        )}
        
        {message.content && (
          <p className="whitespace-pre-wrap break-words">{message.content}</p>
        )}
        
        {renderAttachment()}
        
        <div className={`flex items-center justify-between text-xs mt-1 ${
          isOwn ? 'text-primary-100' : 'text-gray-500 dark:text-gray-400'
        }`}>
          <span>{formatMessageTime(message.createdAt)}</span>
          <div className="flex items-center space-x-1">
            {message.isEdited && <span className="italic">edited</span>}
            {getReadStatus()}
          </div>
        </div>
      </div>
    </div>
  );
};

export default MessageBubble;