import { useEffect, useRef } from 'react';
import { wsClient } from '../api/websocket';

interface SubscriptionConfig {
  table: string;
  event?: '*' | 'INSERT' | 'UPDATE' | 'DELETE';
  filter?: string;
}

type ChangeCallback = () => void;

export function useRealtime(
  config: SubscriptionConfig,
  callback: ChangeCallback,
  enabled: boolean = true
): void {
  const callbackRef = useRef(callback);

  useEffect(() => {
    callbackRef.current = callback;
  }, [callback]);

  useEffect(() => {
    if (!enabled) return;

    const wrappedCallback = () => {
      callbackRef.current();
    };

    const unsubscribe = wsClient.subscribe(config.table, wrappedCallback);

    return () => {
      unsubscribe();
    };
  }, [config.table, config.event, config.filter, enabled]);
}

export function useInventoryRealtime(
  companyId: string | null,
  onChange: ChangeCallback
): void {
  const onChangeRef = useRef(onChange);
  useEffect(() => {
    onChangeRef.current = onChange;
  }, [onChange]);

  useEffect(() => {
    if (!companyId) return;

    const wrappedCallback = () => onChangeRef.current();

    const unsub1 = wsClient.subscribe('inventory_records', wrappedCallback);
    const unsub2 = wsClient.subscribe('product_inventory_records', wrappedCallback);

    return () => {
      unsub1();
      unsub2();
    };
  }, [companyId]);
}

export function usePlanRealtime(
  companyId: string | null,
  onChange: ChangeCallback
): void {
  const onChangeRef = useRef(onChange);
  useEffect(() => {
    onChangeRef.current = onChange;
  }, [onChange]);

  useEffect(() => {
    if (!companyId) return;

    const wrappedCallback = () => onChangeRef.current();

    const unsub = wsClient.subscribe('inventory_records', wrappedCallback);

    return () => {
      unsub();
    };
  }, [companyId]);
}

export function triggerRealtimeRefresh(_table: string): void {
  // no-op: server pushes changes via WebSocket
}
