import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/components/ui/use-toast';
import { logStatusChange } from '@/lib/violationTimelineLogger';

export function useViolations(associationId) {
  const [violations, setViolations] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const { toast } = useToast();

  const fetchViolations = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      let query = supabase.from('violations').select('*');

      if (associationId && associationId !== 'all') {
        query = query.eq('association_id', associationId);
      }

      const { data, error: fetchError } = await query.order('created_at', { ascending: false });

      if (fetchError) throw fetchError;
      setViolations(data || []);
    } catch (err) {
      console.error('Error fetching violations:', err);
      const errorMsg = 'Failed to load violations. Please try again later.';
      setError(errorMsg);
      toast({ variant: 'destructive', title: 'Data Load Error', description: errorMsg });
      setViolations([]);
    } finally {
      setLoading(false);
    }
  }, [associationId, toast]);

  useEffect(() => {
    fetchViolations();
  }, [fetchViolations]);

  const updateViolationStatus = async (id, status) => {
    try {
      const { data: prev } = await supabase.from('violations').select('status').eq('id', id).maybeSingle();
      const { error } = await supabase.from('violations').update({ status }).eq('id', id);
      if (error) throw error;
      if (prev?.status !== status) {
        await logStatusChange(id, prev?.status || null, status);
      }
      fetchViolations();
      return true;
    } catch (err) {
      console.error('Error updating violation status:', err);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to update status.' });
      return false;
    }
  };

  return { violations, loading, error, refetch: fetchViolations, updateViolationStatus };
}
