import { useEffect, useCallback } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { supabase } from '@/integrations/supabase/client';
import { RealtimeChannel } from '@supabase/supabase-js';

interface UseRealtimeOptions {
  channel?: string;
  table?: string;
  onMessage?: (message: Record<string, unknown>) => void;
  onInsert?: (data: Record<string, unknown>) => void;
  onUpdate?: (data: Record<string, unknown>) => void;
  onDelete?: (data: Record<string, unknown>) => void;
  enabled?: boolean;
}

export function useRealtime(options: UseRealtimeOptions = {}) {
  const { user } = useAuth();
  const { table, onInsert, onUpdate, onDelete, enabled = true } = options;

  // Subscribe to table changes via Supabase Realtime
  useEffect(() => {
    if (!enabled || !user || !table) return;

    const channel: RealtimeChannel = supabase
      .channel(`realtime-${table}`)
      .on(
        'postgres_changes',
        {
          event: '*',
          schema: 'public',
          table: table,
        },
        (payload) => {
          if (payload.eventType === 'INSERT' && onInsert) {
            onInsert(payload.new as Record<string, unknown>);
          } else if (payload.eventType === 'UPDATE' && onUpdate) {
            onUpdate(payload.new as Record<string, unknown>);
          } else if (payload.eventType === 'DELETE' && onDelete) {
            onDelete(payload.old as Record<string, unknown>);
          }
        }
      )
      .subscribe();

    return () => {
      supabase.removeChannel(channel);
    };
  }, [table, enabled, user, onInsert, onUpdate, onDelete]);

  const subscribe = useCallback((channelName: string, handler: (message: Record<string, unknown>) => void) => {
    const channel = supabase
      .channel(channelName)
      .on('broadcast', { event: 'message' }, (payload) => {
        handler(payload.payload as Record<string, unknown>);
      })
      .subscribe();

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

  return {
    isConnected: true, // Supabase manages connection state internally
    subscribe,
  };
}

export default useRealtime;
