import { createClient } from '@supabase/supabase-js';
import { io } from 'socket.io-client';

// Supabase client
const supabaseUrl = import.meta.env.VITE_SUPABASE_URL || 'http://127.0.0.1:3000';
const supabaseKey = import.meta.env.VITE_SUPABASE_ANON_KEY || 'sb_publishable_ACJWlzQHlZjBrEguHvfOxg_3BJgxAaH';

export const supabase = createClient(supabaseUrl, supabaseKey);

// Socket.IO client
const socketUrl = import.meta.env.VITE_SOCKET_URL || 'http://localhost:3000';
export const socket = io(socketUrl, {
  autoConnect: false,
  transports: ['websocket', 'polling'],
});

// Connect socket when user is authenticated
export const connectSocket = (userId) => {
  if (!socket.connected) {
    socket.auth = { userId };
    socket.connect();
  }
};

export const disconnectSocket = () => {
  if (socket.connected) {
    socket.disconnect();
  }
};

// Messaging API
export const messagingService = {
  // Get all conversations for a user
  async getConversations(userId) {
    const { data, error } = await supabase
      .from('conversation_participants')
      .select(`
        conversation_id,
        conversations (
          id,
          type,
          title,
          description,
          avatar_url,
          created_at,
          updated_at
        )
      `)
      .eq('user_id', userId)
      .order('conversations(updated_at)', { ascending: false });

    if (error) throw error;
    return data?.map(p => p.conversations) || [];
  },

  // Get messages for a conversation
  async getMessages(conversationId, limit = 50) {
    const { data, error } = await supabase
      .from('messages')
      .select('*')
      .eq('conversation_id', conversationId)
      .order('created_at', { ascending: false })
      .limit(limit);

    if (error) throw error;
    return (data || []).reverse();
  },

  // Send a message
  async sendMessage(conversationId, senderId, content) {
    const { data, error } = await supabase
      .from('messages')
      .insert({
        conversation_id: conversationId,
        sender_id: senderId,
        content_encrypted: content, // TODO: Add actual encryption
        content_type: 'text',
      })
      .select()
      .single();

    if (error) throw error;

    // Emit via socket for real-time
    socket.emit('message:send', {
      conversationId,
      message: data,
    });

    return data;
  },

  // Create a new conversation
  async createConversation(type, title, participantIds) {
    const { data: conversation, error: convError } = await supabase
      .from('conversations')
      .insert({ type, title })
      .select()
      .single();

    if (convError) throw convError;

    // Add participants
    const participants = participantIds.map(userId => ({
      conversation_id: conversation.id,
      user_id: userId,
      role: 'member',
    }));

    const { error: partError } = await supabase
      .from('conversation_participants')
      .insert(participants);

    if (partError) throw partError;

    return conversation;
  },

  // Subscribe to new messages in a conversation
  subscribeToMessages(conversationId, callback) {
    const channel = supabase
      .channel(`messages:${conversationId}`)
      .on(
        'postgres_changes',
        {
          event: 'INSERT',
          schema: 'public',
          table: 'messages',
          filter: `conversation_id=eq.${conversationId}`,
        },
        (payload) => {
          callback(payload.new);
        }
      )
      .subscribe();

    return () => {
      supabase.removeChannel(channel);
    };
  },
};

// Socket event handlers
socket.on('connect', () => {
  console.log('Socket connected:', socket.id);
});

socket.on('disconnect', () => {
  console.log('Socket disconnected');
});

socket.on('message:new', (message) => {
  console.log('New message received:', message);
  // This will be handled by the React context
});

socket.on('error', (error) => {
  console.error('Socket error:', error);
});
