import { useState, useEffect, useCallback } from 'react';
import { chatApi, Chat, Message, User } from '@/services/chatApi';

export const useChat = () => {
  const [chats, setChats] = useState<Chat[]>([]);
  const [messages, setMessages] = useState<Message[]>([]);
  const [onlineUsers, setOnlineUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Load chats
  const loadChats = useCallback(async () => {
    try {
      setLoading(true);
      const chatsData = await chatApi.getChats();
      setChats(chatsData);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load chats');
    } finally {
      setLoading(false);
    }
  }, []);

  // Load messages for a specific chat
  const loadMessages = useCallback(async (chatId: string) => {
    try {
      setLoading(true);
      const messagesData = await chatApi.getMessages(chatId);
      setMessages(messagesData);
      // Mark as read
      await chatApi.markAsRead(chatId);
      // Update chat unread count
      setChats(prev => prev.map(chat => 
        chat.id === chatId ? { ...chat, unreadCount: 0 } : chat
      ));
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load messages');
    } finally {
      setLoading(false);
    }
  }, []);

  // Send a message
  const sendMessage = useCallback(async (chatId: string, content: string) => {
    try {
      const newMessage = await chatApi.sendMessage(chatId, content);
      setMessages(prev => [...prev, newMessage]);
      
      // Update chat with new last message
      setChats(prev => prev.map(chat => 
        chat.id === chatId 
          ? { 
              ...chat, 
              lastMessage: newMessage,
              lastActivity: new Date().toISOString()
            } 
          : chat
      ));
      
      return newMessage;
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to send message');
      throw err;
    }
  }, []);

  // Search users
  const searchUsers = useCallback(async (query: string): Promise<User[]> => {
    try {
      if (!query.trim()) return [];
      return await chatApi.searchUsers(query);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to search users');
      return [];
    }
  }, []);

  // Create new chat
  const createChat = useCallback(async (participantIds: string[]) => {
    try {
      const newChat = await chatApi.createChat(participantIds);
      setChats(prev => [newChat, ...prev]);
      return newChat;
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to create chat');
      throw err;
    }
  }, []);

  // Load online users
  const loadOnlineUsers = useCallback(async () => {
    try {
      const users = await chatApi.getOnlineUsers();
      setOnlineUsers(users);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load online users');
    }
  }, []);

  // Get chat by ID
  const getChatById = useCallback((chatId: string) => {
    return chats.find(chat => chat.id === chatId);
  }, [chats]);

  // Clear error
  const clearError = useCallback(() => {
    setError(null);
  }, []);

  // Initial load
  useEffect(() => {
    loadChats();
    loadOnlineUsers();
  }, [loadChats, loadOnlineUsers]);

  return {
    chats,
    messages,
    onlineUsers,
    loading,
    error,
    loadChats,
    loadMessages,
    sendMessage,
    searchUsers,
    createChat,
    loadOnlineUsers,
    getChatById,
    clearError
  };
};