import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { CollectionSyncManager } from '@/lib/CollectionSyncManager';
import { useToast } from '@/hooks/use-toast';

export const COLLECTION_UPDATE_EVENT = 'collection-update-event';

export function useCollectionSync(associationId = null) {
  const [syncStatus, setSyncStatus] = useState('idle');
  const [lastSyncTime, setLastSyncTime] = useState(null);
  const [syncError, setSyncError] = useState(null);
  const { toast } = useToast();

  const handleRealtimeUpdate = useCallback((payload) => {
    setLastSyncTime(new Date());
    window.dispatchEvent(new CustomEvent(COLLECTION_UPDATE_EVENT, { 
      detail: { type: payload.eventType, table: payload.table, data: payload.new }
    }));
  }, []);

  useEffect(() => {
    const filter = associationId ? `association_id=eq.${associationId}` : undefined;

    const channel = supabase.channel(`sync-room-${associationId || 'global'}`)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'collections', filter }, handleRealtimeUpdate)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'owners', filter }, handleRealtimeUpdate)
      .subscribe();

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

  const triggerManualSync = useCallback(async (type, id) => {
    setSyncStatus('syncing');
    setSyncError(null);

    let result;
    if (type === 'collection') {
      result = await CollectionSyncManager.syncCollectionToOwner(id);
    } else if (type === 'owner') {
      result = await CollectionSyncManager.syncOwnerToCollection(id);
    }

    if (result?.success) {
      setSyncStatus('success');
      setLastSyncTime(new Date());
      toast({ title: "Sync Successful", description: "Records have been synchronized." });
      window.dispatchEvent(new CustomEvent(COLLECTION_UPDATE_EVENT, { detail: { type: 'MANUAL_SYNC', id }}));
      setTimeout(() => setSyncStatus('idle'), 3000);
    } else {
      setSyncStatus('error');
      setSyncError(result?.error);
      toast({ variant: "destructive", title: "Sync Failed", description: result?.error || "An unknown error occurred" });
    }
  }, [toast]);

  const reconcileAll = useCallback(async () => {
    if (!associationId) return;
    setSyncStatus('syncing');
    try {
      const report = await CollectionSyncManager.reconcileData(associationId);
      setSyncStatus('success');
      setLastSyncTime(new Date());
      toast({ title: "Reconciliation Complete", description: `Fixed ${report.fixed} mismatches. ${report.errors} errors.` });
      window.dispatchEvent(new CustomEvent(COLLECTION_UPDATE_EVENT, { detail: { type: 'RECONCILIATION', associationId }}));
    } catch (err) {
      setSyncStatus('error');
      setSyncError(err.message);
      toast({ variant: "destructive", title: "Reconciliation Failed", description: err.message });
    }
  }, [associationId, toast]);

  return { syncStatus, lastSyncTime, syncError, triggerManualSync, reconcileAll };
}
