import React, { useState, useEffect } from 'react';
import { useAuth } from '../../contexts/AuthContext';
import { useSocket } from '../../contexts/SocketContext';
import Sidebar from './Sidebar';
import UserSearch from './UserSearch';
import ChatArea from '../Chat/ChatArea';
import { conversationService } from '../../services/api';
import { X } from 'lucide-react';

const Dashboard = ({ user, onLogout }) => {
  const { logout } = useAuth();
  const { socket, isConnected } = useSocket();
  const [conversations, setConversations] = useState([]);
  const [selectedConversation, setSelectedConversation] = useState(null);
  const [messages, setMessages] = useState([]);
  const [onlineUsers, setOnlineUsers] = useState(new Set());
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState('');
  const [showNewConversation, setShowNewConversation] = useState(false);

  // بارگیری مکالمات هنگام بارگذاری اولیه
  useEffect(() => {
    loadConversations();
  }, []);

  // اشتراک در رویدادهای سوکت
  useEffect(() => {
    if (!socket || !isConnected) return;

    // گرفتن وضعیت آنلاین کاربران
    socket.emit('get-online-users');
    
    // مدیریت رویدادهای سوکت
    const setupSocketListeners = () => {
      socket.on('message:receive', handleMessageReceive);
      socket.on('message:read', handleMessageRead);
      socket.on('conversation:updated', handleConversationUpdate);
      socket.on('conversation:created', handleConversationCreate);
      socket.on('user:status', handleUserStatusChange);
      socket.on('typing:start', handleTypingStart);
      socket.on('typing:stop', handleTypingStop);
    };

    const cleanupSocketListeners = () => {
      socket.off('message:receive', handleMessageReceive);
      socket.off('message:read', handleMessageRead);
      socket.off('conversation:updated', handleConversationUpdate);
      socket.off('conversation:created', handleConversationCreate);
      socket.off('user:status', handleUserStatusChange);
      socket.off('typing:start', handleTypingStart);
      socket.off('typing:stop', handleTypingStop);
    };

    setupSocketListeners();
    return cleanupSocketListeners;
  }, [socket, isConnected, selectedConversation]);

  const loadConversations = async () => {
    try {
      setIsLoading(true);
      setError('');
      
      const response = await conversationService.getAll();
      setConversations(response.conversations || []);
      
      // اگر مکالمه ای وجود داشته باشد، اولین مکالمه را انتخاب کن
      if (response.conversations && response.conversations.length > 0) {
        handleSelectConversation(response.conversations[0]);
      }
    } catch (err) {
      console.error('Error loading conversations:', err);
      setError('Failed to load conversations. Please try again later.');
    } finally {
      setIsLoading(false);
    }
  };

  const handleSelectConversation = async (conversation) => {
    setSelectedConversation(conversation);
    
    try {
      // بارگیری پیام‌های مکالمه
      const response = await conversationService.getMessages(conversation._id);
      setMessages(response.messages || []);
      
      // علامت‌گذاری پیام‌های خوانده شده
      if (socket && socket.connected) {
        socket.emit('message:read-all', {
          conversationId: conversation._id
        });
      }
      
      // به‌روزرسانی لیست مکالمات
      setConversations(prev => prev.map(conv => 
        conv._id === conversation._id ? { ...conv, unreadCount: 0 } : conv
      ));
    } catch (err) {
      console.error('Error loading messages:', err);
      setError('Failed to load messages for this conversation.');
    }
  };

  const handleNewMessage = (message) => {
    // اضافه کردن پیام به لیست پیام‌ها
    setMessages(prev => [...prev, message]);
    
    // به‌روزرسانی آخرین پیام در مکالمه
    if (selectedConversation) {
      setConversations(prev => prev.map(conv => 
        conv._id === selectedConversation._id 
          ? { ...conv, lastMessage: message, updatedAt: new Date() } 
          : conv
      ));
    }
  };

  const handleConversationUpdate = (data) => {
    if (!data.conversationId) return;
    
    setConversations(prev => prev.map(conv => 
      conv._id === data.conversationId ? { ...conv, ...data } : conv
    ));
  };

  const handleConversationCreate = (conversation) => {
    setConversations(prev => [conversation, ...prev]);
    setSelectedConversation(conversation);
  };

  const handleUserStatusChange = (data) => {
    if (data.userId) {
      if (data.status === 'online') {
        setOnlineUsers(prev => new Set(prev).add(data.userId));
      } else {
        setOnlineUsers(prev => {
          const newSet = new Set(prev);
          newSet.delete(data.userId);
          return newSet;
        });
      }
    }
  };

  const handleTypingStart = (data) => {
    if (selectedConversation && data.conversationId === selectedConversation._id) {
      console.log(`${data.userId} is typing...`);
    }
  };

  const handleTypingStop = (data) => {
    if (selectedConversation && data.conversationId === selectedConversation._id) {
      console.log(`${data.userId} stopped typing`);
    }
  };

  const handleMessageReceive = (message) => {
    // اگر پیام مربوط به مکالمه فعلی باشد
    if (selectedConversation && selectedConversation._id === message.conversation) {
      setMessages(prev => [...prev, message]);
    } else {
      // به‌روزرسانی تعداد پیام‌های خوانده نشده
      setConversations(prev => prev.map(conv => 
        conv._id === message.conversation 
          ? { ...conv, unreadCount: (conv.unreadCount || 0) + 1 } 
          : conv
      ));
    }
  };

  const handleMessageRead = (data) => {
    if (selectedConversation && selectedConversation._id === data.conversationId) {
      setMessages(prev => prev.map(msg => 
        msg._id === data.messageId ? { ...msg, readBy: [...(msg.readBy || []), { user: data.userId }] } : msg
      ));
    }
  };

  const handleNewConversation = () => {
    setShowNewConversation(true);
  };

  const handleConversationCreated = (conversation) => {
    setShowNewConversation(false);
    handleSelectConversation(conversation);
  };

  const handleLogoutUser = async () => {
    try {
      await logout();
      onLogout();
    } catch (error) {
      console.error('Logout failed:', error);
    }
  };

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center p-4">
        <div className="bg-white dark:bg-gray-800 rounded-xl p-6 max-w-md w-full text-center shadow-lg">
          <div className="w-12 h-12 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mx-auto mb-4">
            <span className="text-red-500 text-2xl">⚠️</span>
          </div>
          <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Connection Error</h2>
          <p className="text-gray-600 dark:text-gray-400 mb-4">{error}</p>
          <button
            onClick={loadConversations}
            className="bg-primary-500 hover:bg-primary-600 text-white font-medium py-2 px-6 rounded-lg transition-colors"
          >
            Try Again
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="flex h-screen bg-gray-50 dark:bg-gray-900">
      {/* Sidebar */}
      <Sidebar
        conversations={conversations}
        selectedConversation={selectedConversation}
        onSelectConversation={handleSelectConversation}
        onNewConversation={handleNewConversation}
        onlineUsers={onlineUsers}
      />

      {/* Main Content */}
      <div className="flex-1 flex flex-col min-h-0">
        {isLoading ? (
          <div className="flex-1 flex items-center justify-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-500"></div>
          </div>
        ) : !selectedConversation ? (
          <div className="flex-1 flex items-center justify-center bg-gray-50 dark:bg-gray-800">
            <div className="text-center p-8 max-w-md">
              <div className="w-24 h-24 mx-auto mb-6 bg-gradient-to-br from-blue-100 to-blue-200 dark:from-blue-900 dark:to-blue-800 rounded-full flex items-center justify-center">
                <svg className="w-12 h-12 text-blue-500 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                </svg>
              </div>
              <h3 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">
                Welcome to YSNRFD Messenger
              </h3>
              <p className="text-gray-600 dark:text-gray-400 mb-6">
                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 dark:text-gray-400">
                <div className="flex items-center justify-center space-x-2">
                  <span className="w-2 h-2 bg-green-500 rounded-full"></span>
                  <span>Real-time messaging</span>
                </div>
                <div className="flex items-center justify-center space-x-2">
                  <span className="w-2 h-2 bg-green-500 rounded-full"></span>
                  <span>File sharing</span>
                </div>
                <div className="flex items-center justify-center space-x-2">
                  <span className="w-2 h-2 bg-green-500 rounded-full"></span>
                  <span>Group chats</span>
                </div>
                <div className="flex items-center justify-center space-x-2">
                  <span className="w-2 h-2 bg-green-500 rounded-full"></span>
                  <span>Read receipts</span>
                </div>
              </div>
            </div>
          </div>
        ) : (
          <>
            <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between px-4 sm:px-6 py-3">
              <div className="flex items-center space-x-3">
                <button
                  className="sm:hidden p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 focus:outline-none"
                  onClick={() => document.querySelector('.sidebar-container')?.classList.toggle('hidden')}
                >
                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h7" />
                  </svg>
                </button>
                <div className="flex items-center space-x-3">
                  <div className="w-10 h-10 bg-gradient-to-br from-primary-400 to-primary-600 rounded-full flex items-center justify-center text-white font-medium">
                    {selectedConversation.type === 'direct' ? (
                      <span>{selectedConversation.participants.find(p => p.user._id !== user.id)?.user.displayName.charAt(0) || 'U'}</span>
                    ) : (
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                      </svg>
                    )}
                  </div>
                  <div>
                    <h1 className="text-lg font-semibold text-gray-900 dark:text-white">
                      {selectedConversation.type === 'direct'
                        ? selectedConversation.participants.find(p => p.user._id !== user.id)?.user.displayName
                        : selectedConversation.name}
                    </h1>
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                      {selectedConversation.type === 'direct'
                        ? 'Direct message'
                        : `${selectedConversation.participants.length} members`}
                    </p>
                  </div>
                </div>
              </div>
              <div className="flex items-center space-x-3">
                <button
                  onClick={handleLogoutUser}
                  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"
                  title="Logout"
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                  </svg>
                </button>
              </div>
            </div>

            {/* Chat Area */}
            <ChatArea
              conversation={selectedConversation}
              messages={messages}
              onNewMessage={handleNewMessage}
              onConversationUpdate={handleConversationUpdate}
            />
          </>
        )}
      </div>

      {/* User Search Modal */}
      {showNewConversation && (
        <UserSearch
          onClose={() => setShowNewConversation(false)}
          onConversationCreated={handleConversationCreated}
        />
      )}
    </div>
  );
};

export default Dashboard;