import React, { useState } from 'react';
import { LogOut, MessageCircle, Users, Search, Image, Music } from 'lucide-react';
import MessageInput from '/Users/ysnrfd/Desktop/ysnrfd_messenger2/frontend/src/components/Chat/MessageInput';

const Dashboard = ({ user, onLogout }) => {
  const [selectedConversation, setSelectedConversation] = useState(null);
  const [messages, setMessages] = useState([]);

  // Mock conversations data
  const conversations = [
    {
      id: 1,
      name: 'John Doe',
      lastMessage: 'Hey, how are you?',
      unread: 2,
      online: true
    },
    {
      id: 2,
      name: 'Sarah Smith',
      lastMessage: 'Meeting at 3 PM',
      unread: 0,
      online: false
    },
    {
      id: 3,
      name: 'Work Group',
      lastMessage: 'Mike: Project update ready',
      unread: 5,
      online: true,
      isGroup: true
    }
  ];

  // Mock messages data
  const mockMessages = [
    { id: 1, text: 'Hello there!', sender: 'other', time: '10:30 AM' },
    { id: 2, text: 'Hi! How are you doing?', sender: 'me', time: '10:31 AM' },
    { id: 3, text: 'I\'m good, thanks! Working on the new project.', sender: 'other', time: '10:32 AM' },
    { id: 4, text: 'That sounds great! Let me know if you need any help.', sender: 'me', time: '10:33 AM' }
  ];

  const handleSendMessage = (messageData) => {
    const message = {
      id: Date.now(),
      text: messageData.content,
      sender: 'me',
      time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
      type: messageData.type,
      attachment: messageData.attachment
    };

    setMessages([...messages, message]);
  };

  const handleSelectConversation = (conversation) => {
    setSelectedConversation(conversation);
    setMessages(mockMessages); // Load mock messages
  };

  // Render message with attachment
  const renderMessage = (message) => {
    if (message.attachment) {
      return (
        <div className="space-y-2">
          <p className="text-sm">{message.text}</p>
          <div className="p-3 bg-blue-50 rounded-lg border border-blue-200">
            <div className="flex items-center space-x-2 text-sm text-blue-700">
              {message.attachment.mimeType.startsWith('image/') && <Image className="w-4 h-4" />}
              {message.attachment.mimeType.startsWith('audio/') && <Music className="w-4 h-4" />}
              <span className="font-medium">{message.attachment.originalName}</span>
              <span className="text-blue-600">({formatFileSize(message.attachment.size)})</span>
            </div>
          </div>
        </div>
      );
    }
    
    return <p className="text-sm">{message.text}</p>;
  };

  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  return (
    <div className="flex h-screen bg-gray-50">
      {/* Sidebar */}
      <div className="w-80 bg-white border-r border-gray-200 flex flex-col">
        {/* Header */}
        <div className="p-4 border-b border-gray-200">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center">
                <MessageCircle className="w-6 h-6 text-white" />
              </div>
              <div>
                <h1 className="text-lg font-bold text-gray-900">YSNRFD Messenger</h1>
                <p className="text-xs text-gray-500">Welcome, {user.displayName}</p>
              </div>
            </div>
            <button
              onClick={onLogout}
              className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              title="Logout"
            >
              <LogOut className="w-5 h-5 text-gray-600" />
            </button>
          </div>

          {/* Search */}
          <div className="mt-4 relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
            <input
              type="text"
              placeholder="Search conversations..."
              className="w-full pl-10 pr-4 py-2 bg-gray-100 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
            />
          </div>
        </div>

        {/* Conversations List */}
        <div className="flex-1 overflow-y-auto">
          {conversations.map((conversation) => (
            <div
              key={conversation.id}
              onClick={() => handleSelectConversation(conversation)}
              className={`p-4 border-b border-gray-100 hover:bg-gray-50 cursor-pointer transition-colors ${
                selectedConversation?.id === conversation.id ? 'bg-blue-50 border-blue-200' : ''
              }`}
            >
              <div className="flex items-center space-x-3">
                <div className="relative">
                  <div className="w-12 h-12 bg-gradient-to-br from-blue-400 to-blue-600 rounded-full flex items-center justify-center text-white font-medium">
                    {conversation.isGroup ? (
                      <Users className="w-6 h-6" />
                    ) : (
                      conversation.name.charAt(0)
                    )}
                  </div>
                  {conversation.online && (
                    <div className="absolute bottom-0 right-0 w-3 h-3 bg-green-500 border-2 border-white rounded-full"></div>
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between">
                    <h3 className="text-sm font-semibold text-gray-900 truncate">
                      {conversation.name}
                    </h3>
                    <span className="text-xs text-gray-500">10:30 AM</span>
                  </div>
                  <p className="text-sm text-gray-600 truncate">
                    {conversation.lastMessage}
                  </p>
                </div>
                {conversation.unread > 0 && (
                  <div className="bg-blue-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center">
                    {conversation.unread}
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Main Chat Area */}
      <div className="flex-1 flex flex-col">
        {selectedConversation ? (
          <>
            {/* Chat Header */}
            <div className="bg-white border-b border-gray-200 p-4">
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-gradient-to-br from-blue-400 to-blue-600 rounded-full flex items-center justify-center text-white font-medium">
                    {selectedConversation.isGroup ? (
                      <Users className="w-6 h-6" />
                    ) : (
                      selectedConversation.name.charAt(0)
                    )}
                  </div>
                  <div>
                    <h2 className="text-lg font-semibold text-gray-900">
                      {selectedConversation.name}
                    </h2>
                    <p className="text-sm text-gray-500">
                      {selectedConversation.online ? 'Online' : 'Last seen recently'}
                    </p>
                  </div>
                </div>
              </div>
            </div>

            {/* Messages Area */}
            <div className="flex-1 overflow-y-auto p-4 space-y-4 bg-gray-50">
              {messages.map((message) => (
                <div
                  key={message.id}
                  className={`flex ${message.sender === 'me' ? 'justify-end' : 'justify-start'}`}
                >
                  <div
                    className={`max-w-xs lg:max-w-md px-4 py-2 rounded-2xl ${
                      message.sender === 'me'
                        ? 'bg-blue-500 text-white rounded-br-none'
                        : 'bg-white text-gray-900 rounded-bl-none shadow-sm'
                    }`}
                  >
                    {renderMessage(message)}
                    <p
                      className={`text-xs mt-1 ${
                        message.sender === 'me' ? 'text-blue-100' : 'text-gray-500'
                      }`}
                    >
                      {message.time}
                    </p>
                  </div>
                </div>
              ))}
            </div>

            {/* Message Input */}
            <MessageInput onSendMessage={handleSendMessage} />
          </>
        ) : (
          <div className="flex-1 flex items-center justify-center bg-gray-50">
            <div className="text-center p-8">
              <div className="w-24 h-24 mx-auto mb-6 bg-gradient-to-br from-blue-100 to-blue-200 rounded-full flex items-center justify-center">
                <MessageCircle className="w-12 h-12 text-blue-500" />
              </div>
              <h3 className="text-2xl font-bold text-gray-900 mb-2">
                Welcome to YSNRFD Messenger
              </h3>
              <p className="text-gray-600 mb-6 max-w-md">
                Select a conversation from the sidebar to start messaging, or create a new one to begin connecting.
              </p>
              <div className="space-y-3 text-sm text-gray-500">
                <p>✅ Real-time messaging</p>
                <p>✅ File sharing</p>
                <p>✅ Group chats</p>
                <p>✅ Read receipts</p>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default Dashboard;