import React, { useState, useRef, useCallback } from 'react';
import { Send, Paperclip, Smile, X, Image, Music, FileText } from 'lucide-react';
import { useWebSocket } from '../../hooks/useWebSocket';
import { useFileUpload } from '../../hooks/useFileUpload';
import { validateFile, formatFileSize } from '../../utils/fileValidation';

const MessageInput = ({ conversation, onSendMessage }) => {
  const [message, setMessage] = useState('');
  const [isTyping, setIsTyping] = useState(false);
  const [filePreview, setFilePreview] = useState(null);
  const fileInputRef = useRef();
  const { sendMessage } = useWebSocket();
  const { uploadFile, uploading, progress, error: uploadError, reset: resetUpload } = useFileUpload();
  const typingTimeoutRef = useRef();

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!message.trim() && !filePreview) return;
    
    // توقف تایپینگ
    stopTyping();
    
    if (filePreview) {
      // ارسال فایل
      await sendFileMessage();
    } else {
      // ارسال پیام متنی
      sendTextMessage();
    }
    
    // بازنشانی حالت
    setMessage('');
    setFilePreview(null);
    resetUpload();
  };

  const sendTextMessage = () => {
    if (!message.trim()) return;
    
    const messageData = {
      conversationId: conversation._id,
      content: message.trim(),
      type: 'text'
    };
    
    // ارسال از طریق سوکت
    if (sendMessage) {
      sendMessage('message:send', messageData);
    }
    
    // به‌روزرسانی لیست پیام‌ها
    onSendMessage({
      ...messageData,
      _id: `temp-${Date.now()}`,
      sender: { _id: 'current-user' },
      createdAt: new Date(),
      status: 'sending'
    });
  };

  const sendFileMessage = async () => {
    if (!filePreview) return;
    
    try {
      setLoading(true);
      
      // آپلود فایل
      const response = await uploadFile(filePreview.file);
      
      // آماده‌سازی داده پیام
      const fileName = filePreview.file.name;
      const messageData = {
        conversationId: conversation._id,
        content: message.trim() || `Sent ${getFileTypeDescription(filePreview.file.type)}`,
        type: getMessageType(filePreview.file.type),
        attachment: {
          url: response.file.url,
          filename: response.file.fileName,
          originalName: fileName,
          mimeType: filePreview.file.type,
          size: filePreview.file.size,
          thumbnail: response.file.thumbnail
        }
      };
      
      // ارسال از طریق سوکت
      if (sendMessage) {
        sendMessage('message:send', messageData);
      }
      
      // به‌روزرسانی لیست پیام‌ها
      onSendMessage({
        ...messageData,
        _id: `temp-${Date.now()}`,
        sender: { _id: 'current-user' },
        createdAt: new Date(),
        status: 'sending'
      });
    } catch (error) {
      console.error('Failed to send file message:', error);
      alert('Failed to send file. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const handleInputChange = (e) => {
    setMessage(e.target.value);
    
    if (!isTyping) {
      startTyping();
    }
    
    // بازنشانی تایمر تایپینگ
    clearTimeout(typingTimeoutRef.current);
    typingTimeoutRef.current = setTimeout(stopTyping, 1000);
  };

  const startTyping = () => {
    if (!isTyping && sendMessage) {
      setIsTyping(true);
      sendMessage('typing:start', { conversationId: conversation._id });
    }
  };

  const stopTyping = () => {
    if (isTyping && sendMessage) {
      setIsTyping(false);
      sendMessage('typing:stop', { conversationId: conversation._id });
    }
  };

  const handleFileSelect = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    
    try {
      validateFile(file);
      
      const previewUrl = URL.createObjectURL(file);
      setFilePreview({
        file,
        previewUrl,
        name: file.name,
        size: file.size,
        type: file.type
      });
      
      // بازنشانی input
      fileInputRef.current.value = '';
    } catch (error) {
      alert(error.message);
    }
  };

  const removeFile = () => {
    if (filePreview?.previewUrl) {
      URL.revokeObjectURL(filePreview.previewUrl);
    }
    setFilePreview(null);
    resetUpload();
  };

  const getFileTypeDescription = (mimeType) => {
    if (mimeType.startsWith('image/')) return 'an image';
    if (mimeType.startsWith('audio/')) return 'an audio file';
    if (mimeType === 'application/pdf') return 'a PDF';
    if (mimeType.startsWith('text/')) return 'a text file';
    return 'a file';
  };

  const getMessageType = (mimeType) => {
    if (mimeType.startsWith('image/')) return 'image';
    if (mimeType.startsWith('audio/')) return 'audio';
    return 'file';
  };

  const getFileIcon = (mimeType) => {
    if (mimeType.startsWith('image/')) return <Image className="w-4 h-4 text-gray-500" />;
    if (mimeType.startsWith('audio/')) return <Music className="w-4 h-4 text-gray-500" />;
    return <FileText className="w-4 h-4 text-gray-500" />;
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSubmit(e);
    }
  };

  const handleEmojiSelect = (emojiObject) => {
    setMessage(prev => prev + emojiObject.emoji);
    if (fileInputRef.current) {
      fileInputRef.current.focus();
    }
  };

  return (
    <div className="border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-4">
      {/* Preview فایل */}
      {filePreview && (
        <div className="mb-4 flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">
          <div className="flex items-center space-x-3 flex-1 min-w-0">
            <div className="text-primary-500">
              {getFileIcon(filePreview.type)}
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-medium text-gray-900 dark:text-white truncate">
                {filePreview.name}
              </p>
              <div className="flex items-center space-x-2 text-xs text-gray-500 dark:text-gray-400">
                <span>{formatFileSize(filePreview.size)}</span>
                {uploading && (
                  <div className="flex items-center space-x-1">
                    <div className="w-16 bg-gray-200 dark:bg-gray-600 rounded-full h-1.5">
                      <div 
                        className="bg-primary-500 h-1.5 rounded-full transition-all duration-300"
                        style={{ width: `${progress}%` }}
                      ></div>
                    </div>
                    <span>{progress}%</span>
                  </div>
                )}
              </div>
            </div>
          </div>
          <button
            onClick={removeFile}
            className="p-1 text-gray-500 hover:text-red-500 dark:text-gray-400 dark:hover:text-red-400 hover:bg-gray-200 dark:hover:bg-gray-600 rounded transition-colors"
          >
            <X size={16} />
          </button>
        </div>
      )}
      
      {uploadError && (
        <div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-sm text-red-600 dark:text-red-400">
          {uploadError}
        </div>
      )}

      {/* Input مخفی فایل */}
      <input
        type="file"
        ref={fileInputRef}
        onChange={handleFileSelect}
        accept="image/*,audio/*,.pdf,.txt,.md"
        className="hidden"
      />

      <form onSubmit={handleSubmit} className="flex items-end space-x-2">
        {/* دکمه ضمیمه */}
        <button
          type="button"
          onClick={() => fileInputRef.current?.click()}
          disabled={uploading}
          className="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-700 rounded-lg transition-colors disabled:opacity-50"
          title="Attach file"
        >
          <Paperclip size={20} />
        </button>
        
        {/* Input پیام */}
        <div className="flex-1 min-w-0">
          <textarea
            value={message}
            onChange={handleInputChange}
            onKeyPress={handleKeyPress}
            placeholder="Type a message..."
            className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-2xl focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 resize-none max-h-32"
            rows={1}
            disabled={uploading}
          />
        </div>
        
        {/* دکمه ارسال */}
        <button
          type="submit"
          disabled={(!message.trim() && !filePreview) || uploading}
          className="p-3 bg-primary-500 text-white rounded-full hover:bg-primary-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex-shrink-0"
          title="Send message"
        >
          {uploading ? (
            <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
          ) : (
            <Send size={20} />
          )}
        </button>
      </form>
      
      {/* نشانگر تایپینگ */}
      {isTyping && (
        <div className="text-xs text-gray-500 dark:text-gray-400 mt-2 flex items-center">
          <span className="mr-2">Typing</span>
          <div className="flex space-x-1">
            <div className="w-1.5 h-1.5 bg-gray-500 rounded-full animate-bounce" style={{ animationDelay: '0s' }}></div>
            <div className="w-1.5 h-1.5 bg-gray-500 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }}></div>
            <div className="w-1.5 h-1.5 bg-gray-500 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
          </div>
        </div>
      )}
    </div>
  );
};

export default MessageInput;