'use client';

import { useState, useEffect, useRef } from 'react';
import { useSession } from 'next-auth/react';
import { useWebSocketContext } from '@/context/WebSocketContext';

interface Profile {
  firstName?: string;
  lastName?: string;
  profileImage?: string;
}

interface User {
  id: string;
  email: string;
  profile?: Profile;
}

interface Message {
  id: string;
  content: string;
  createdAt: string;
  project?: {
    id: string;
    title: string;
  };
}

interface Conversation {
  contactId: string;
  contact: User;
  lastMessage: Message;
  lastMessageTime: string;
  unreadCount: number;
}

interface ConversationListProps {
  onSelectConversation: (contactId: string, contact: User) => void;
  selectedContactId?: string;
  onFirstConversationAvailable?: (contactId: string, contact: User) => void;
  shouldSelectFirst?: boolean;
}

export default function ConversationList({ onSelectConversation, selectedContactId, onFirstConversationAvailable, shouldSelectFirst }: ConversationListProps) {
  const { data: session } = useSession();
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [loading, setLoading] = useState(false);
  const [query, setQuery] = useState('');

  const { isConnected, lastMessage } = useWebSocketContext();

  useEffect(() => {
    if (lastMessage) {
      switch (lastMessage.type) {
        case 'new_message':
          if (lastMessage.message) {
            const currentUserId = (session?.user as any)?.id || (session?.user as any)?.email;
            const msgSenderId = lastMessage.message.senderId;
            const msgReceiverId = lastMessage.message.receiverId;
            
            // Update conversation list with new message
            setConversations(prev => {
              const updated = [...prev];
              const conversationIndex = updated.findIndex(conv => 
                conv.contactId === msgSenderId || conv.contactId === msgReceiverId
              );
              
              if (conversationIndex >= 0) {
                // Update existing conversation
                const conversation = { ...updated[conversationIndex] };
                conversation.lastMessage = lastMessage.message;
                conversation.lastMessageTime = lastMessage.message.createdAt;
                
                // Increment unread count if message is from contact
                if (msgSenderId !== currentUserId) {
                  conversation.unreadCount = (conversation.unreadCount || 0) + 1;
                }
                
                // Move conversation to top
                updated.splice(conversationIndex, 1);
                updated.unshift(conversation);
              } else {
                // Add new conversation if it doesn't exist
                // This would happen for new contacts messaging you
                fetchConversations(); // Fallback to full refresh for new contacts
              }
              
              return updated;
            });
          }
          break;
          
        case 'message_read':
          // Update unread count when messages are marked as read
          if (lastMessage.contactId) {
            setConversations(prev => prev.map(conv => 
              conv.contactId === lastMessage.contactId
                ? { ...conv, unreadCount: 0 }
                : conv
            ));
          }
          break;
          
        case 'typing_start':
        case 'typing_stop':
          // Could add typing indicators in conversation list if desired
          break;
          
        default:
          // Handle other message types if needed
          break;
      }
    }
  }, [lastMessage, session]);

  useEffect(() => {
    if (session?.user?.email) {
      fetchConversations();
    }
  }, [session]);

  // Auto-select first conversation when conversations are loaded and shouldSelectFirst is true
  useEffect(() => {
    if (shouldSelectFirst && conversations.length > 0 && onFirstConversationAvailable && !selectedContactId) {
      const firstConversation = conversations[0];
      onFirstConversationAvailable(firstConversation.contactId, firstConversation.contact);
    }
  }, [conversations, shouldSelectFirst, onFirstConversationAvailable, selectedContactId]);

  const fetchConversations = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/messages/conversations');
      if (response.ok) {
        const data = await response.json();
        setConversations(data.data);
      }
    } catch (error) {
    } finally {
      setLoading(false);
    }
  };


  const formatTimeAgo = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffInMinutes = Math.floor((now.getTime() - date.getTime()) / (1000 * 60));

    if (diffInMinutes < 1) return 'Just now';
    if (diffInMinutes < 60) return `${diffInMinutes}m ago`;
    if (diffInMinutes < 1440) return `${Math.floor(diffInMinutes / 60)}h ago`;
    return `${Math.floor(diffInMinutes / 1440)}d ago`;
  };

  const getDisplayName = (user: User) => {
    if (user.profile?.firstName && user.profile?.lastName) {
      return `${user.profile.firstName} ${user.profile.lastName}`;
    }
    return user.email;
  };

  const getProfileImage = (user: User) => {
    return user.profile?.profileImage || '/assets/image/harveyspecter.png';
  };

  const truncateMessage = (content: string, maxLength: number = 50) => {
    if (content.length <= maxLength) return content;
    return content.substring(0, maxLength) + '...';
  };

  if (!session?.user) {
    return null;
  }

  const filtered = conversations.filter((c) => {
    const name = getDisplayName(c.contact).toLowerCase();
    const last = c.lastMessage?.content?.toLowerCase?.() || '';
    const q = query.toLowerCase();
    return name.includes(q) || last.includes(q);
  });

  return (
    <div id="sidepanel">
      <div className="search-wrap" id="search">
        <label htmlFor="search-input">
          <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M19.5308 18.4686L14.8368 13.7755C16.1973 12.1421 16.8757 10.047 16.7309 7.92618C16.5861 5.80531 15.6293 3.82191 14.0593 2.38859C12.4894 0.955257 10.4274 0.18235 8.30212 0.23065C6.17687 0.27895 4.15205 1.14474 2.64888 2.64791C1.14571 4.15108 0.279927 6.1759 0.231627 8.30115C0.183327 10.4264 0.956234 12.4885 2.38956 14.0584C3.82289 15.6283 5.80629 16.5852 7.92715 16.73C10.048 16.8748 12.1431 16.1963 13.7765 14.8358L18.4696 19.5299C18.5393 19.5995 18.622 19.6548 18.713 19.6925C18.8041 19.7302 18.9017 19.7497 19.0002 19.7497C19.0988 19.7497 19.1963 19.7302 19.2874 19.6925C19.3784 19.6548 19.4612 19.5995 19.5308 19.5299C19.6005 19.4602 19.6558 19.3775 19.6935 19.2864C19.7312 19.1954 19.7506 19.0978 19.7506 18.9992C19.7506 18.9007 19.7312 18.8031 19.6935 18.7121C19.6558 18.621 19.6005 18.5383 19.5308 18.4686ZM1.75021 8.49924C1.75021 7.16421 2.14609 5.85917 2.88779 4.74914C3.62949 3.63911 4.6837 2.77394 5.9171 2.26305C7.1505 1.75216 8.5077 1.61849 9.81707 1.87894C11.1264 2.13939 12.3292 2.78226 13.2732 3.72627C14.2172 4.67027 14.8601 5.87301 15.1205 7.18238C15.381 8.49175 15.2473 9.84895 14.7364 11.0823C14.2255 12.3158 13.3603 13.37 12.2503 14.1117C11.1403 14.8534 9.83524 15.2492 8.50021 15.2492C6.71061 15.2473 4.99488 14.5355 3.72944 13.27C2.46399 12.0046 1.7522 10.2888 1.75021 8.49924Z" fill="#404A62"/>
          </svg>                                        
        </label>
        <input 
          type="text" 
          id="search-input"
          placeholder="Search for chats..." 
          value={query}
          onChange={(e) => setQuery(e.target.value)}
        />
      </div>
      
      <div id="contacts">
        {loading ? (
          <div className="p-4 text-center">
            <div className="spinner-border spinner-border-sm" role="status">
              <span className="visually-hidden">Loading...</span>
            </div>
          </div>
        ) : conversations.length === 0 ? (
          <div className="p-4 text-center text-muted">
            <img src="/assets/image/message-chat.svg" alt="" width="48" height="48" className="mb-2 opacity-50" />
            <p className="mb-0">No conversations yet</p>
          </div>
        ) : (
          <ul>
            {filtered.map((conversation) => {
              const isActive = selectedContactId === conversation.contactId;
              const displayName = getDisplayName(conversation.contact);
              const profileImage = getProfileImage(conversation.contact);
              const lastMessageTime = formatTimeAgo(conversation.lastMessageTime);
              const lastMessageContent = conversation.lastMessage ? truncateMessage(conversation.lastMessage.content) : '';
              
              return (
                <li 
                  key={conversation.contactId}
                  className={`contact ${isActive ? 'active' : ''}`}
                  onClick={() => onSelectConversation(conversation.contactId, conversation.contact)}
                >
                  <div className="wrap">
                    <span className="contact-status online"></span>
                    <img src={profileImage} alt={displayName} />
                    <div className="meta">
                      <p className="name">{displayName}</p>
                      {conversation.lastMessage?.project?.title && (
                        <p className="project-name" style={{ fontSize: '12px', color: '#000', margin: '2px' }}>
                          Project: {conversation.lastMessage.project.title}
                        </p>
                      )}
                      <p className="preview">{lastMessageContent}</p>
                    </div>
                    <div className="message-sending-status">
                      {lastMessageTime}
                    </div>
                    {conversation.unreadCount > 0 && (
                      <div className="message-count">
                        {conversation.unreadCount > 99 ? '99+' : conversation.unreadCount}
                      </div>
                    )}
                  </div>
                </li>
              );
            })}
          </ul>
        )}
      </div>
    </div>
  );
}