import React from 'react';
import { usePresence } from '../hooks/usePresence';
import { useAuth } from '../context/useAuth';
import { SendMessageModal } from './SendMessageModal';
import api from '../services/api';

interface OrganizationMember {
    _id: string;
    id: string;
    name: string;
    email: string;
    logto_id: string;
    role: string;
}

interface PendingMessage {
    _id: string;
    message: string;
    toUser: {
        name: string;
        email: string;
    };
}

export const TeamPresence: React.FC = () => {
    const { activeUsers } = usePresence();
    const { appUser } = useAuth();
    const [allMembers, setAllMembers] = React.useState<OrganizationMember[]>([]);
    const [pendingMessages, setPendingMessages] = React.useState<PendingMessage[]>([]);
    const [selectedUser, setSelectedUser] = React.useState<{ id: string; name: string } | null>(null);
    const [isModalOpen, setIsModalOpen] = React.useState(false);

    // Fetch all members
    const fetchMembers = useCallback(async () => {
        try {
            const response = await api.get<OrganizationMember[]>('/users');
            setAllMembers(response.data);
        } catch (error) {
            console.error('Error fetching members:', error);
        }
    }, []);

    // Fetch pending messages
    const fetchPendingMessages = useCallback(async () => {
        try {
            const response = await api.get<PendingMessage[]>('/messages/pending');
            setPendingMessages(response.data);
        } catch (error) {
            console.error('Error fetching pending messages:', error);
        }
    }, []);

    React.useEffect(() => {
        fetchMembers();
        fetchPendingMessages();
        
        const memberInterval = setInterval(fetchMembers, 60000);
        const messageInterval = setInterval(fetchPendingMessages, 30000);
        
        return () => {
            clearInterval(memberInterval);
            clearInterval(messageInterval);
        };
    }, [fetchMembers, fetchPendingMessages]);

    if (allMembers.length === 0) {
        return null;
    }

    // Create a Set of active user IDs for fast lookup
    const activeUserLogtoIds = new Set(activeUsers.map(u => u.logtoId));

    // Create a map of pending messages by recipient ID
    const pendingMessagesByRecipient = new Map(
        (pendingMessages || []).map(msg => [msg.toUser?.email, msg])
    );

    const handleMemberClick = (member: OrganizationMember) => {
        if (member.logto_id === appUser?.logtoId) {
            return; // Don't allow messaging yourself
        }
        setSelectedUser({ id: member.logto_id, name: member.name });
        setIsModalOpen(true);
    };

    const handleModalClose = () => {
        setIsModalOpen(false);
        setSelectedUser(null);
    };

    const handleMessageSent = async () => {
        await fetchPendingMessages();
    };

    const getExistingMessage = (member: OrganizationMember) => {
        const pending = pendingMessagesByRecipient.get(member.email);
        return pending ? { id: pending._id, message: pending.message } : undefined;
    };

    return (
        <>
            <div className="px-6 py-3">
                <div className="mb-2">
                    <span className="text-[10px] font-bold text-text-muted uppercase tracking-[0.2em]">
                        Equipe ({(activeUsers || []).length}/{(allMembers || []).length} online)
                    </span>
                </div>
                <div className="flex flex-wrap gap-2">
                    {(allMembers || []).map((member) => {
                        const isOnline = activeUserLogtoIds.has(member.logto_id);
                        const isCurrentUser = member.logto_id === appUser?.logtoId;
                        const hasPendingMessage = pendingMessagesByRecipient.has(member.email);

                        return (
                            <div
                                key={member._id}
                                className="relative group"
                                onClick={() => !isCurrentUser && handleMemberClick(member)}
                            >
                                <div className={`
                                    w-8 h-8 rounded-full border-2 text-xs font-bold flex items-center justify-center uppercase shadow-sm
                                    transition-all duration-300
                                    ${isOnline
                                        ? 'bg-primary/20 border-primary text-primary ring-2 ring-primary/20 shadow-primary/20'
                                        : 'bg-surface-soft border-border/30 text-text-muted/40 grayscale opacity-40'
                                    }
                                    ${isCurrentUser ? 'ring-2 ring-amber-500 cursor-default' : 'cursor-pointer hover:scale-110'}
                                    ${hasPendingMessage ? 'ring-2 ring-blue-500' : ''}
                                `}>
                                    {member.name.charAt(0)}
                                </div>

                                {/* Online indicator */}
                                {isOnline && (
                                    <span className="absolute bottom-0 right-0 block h-2.5 w-2.5 rounded-full bg-green-500 ring-2 ring-surface animate-pulse" />
                                )}

                                {/* Pending message indicator */}
                                {hasPendingMessage && !isCurrentUser && (
                                    <span className="absolute top-0 right-0 block h-2 w-2 rounded-full bg-blue-500 ring-2 ring-surface" title="Mensagem pendente" />
                                )}

                                {/* Tooltip */}
                                <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-3 py-1.5 bg-surface border border-border/40 shadow-xl rounded-lg opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none z-50">
                                    <div className="text-xs">
                                        <div className="font-bold text-text-main flex items-center gap-2">
                                            {member.name}
                                            {isCurrentUser && <span className="text-amber-500 text-[10px]">(Você)</span>}
                                        </div>
                                        <div className="text-text-muted text-[10px] mt-0.5">{member.email}</div>
                                        <div className={`text-[10px] mt-1 font-semibold ${isOnline ? 'text-green-500' : 'text-text-muted'}`}>
                                            {isOnline ? '🟢 Online' : '⚫ Offline'}
                                        </div>
                                        {!isCurrentUser && (
                                            <div className="text-blue-400 text-[10px] mt-1">
                                                💬 Clique para enviar mensagem
                                            </div>
                                        )}
                                        {hasPendingMessage && (
                                            <div className="text-blue-400 text-[10px] mt-1 font-semibold">
                                                ✉️ Mensagem pendente
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        );
                    })}
                </div>
            </div>

            {/* Message Modal */}
            {selectedUser && (
                <SendMessageModal
                    isOpen={isModalOpen}
                    onClose={handleModalClose}
                    recipientId={selectedUser.id}
                    recipientName={selectedUser.name}
                    existingMessage={getExistingMessage(allMembers.find(m => m.logto_id === selectedUser.id)!)}
                    onMessageSent={handleMessageSent}
                />
            )}
        </>
    );
};

// No the component body I used useCallback so I need to import it
import { useCallback } from 'react';
