import { useState, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/components/ui/use-toast';
import { v4 as uuidv4 } from 'uuid';

export const useViolationTimeline = (violationId, onUpdate) => {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);

  const fetchTimeline = useCallback(async () => {
    try {
      const { data, error } = await supabase
        .from('violations')
        .select('timeline_entries')
        .eq('id', violationId)
        .single();

      if (error) throw error;
      return data?.timeline_entries || [];
    } catch (error) {
      console.error('Error fetching timeline:', error);
      return [];
    }
  }, [violationId]);

  const addEntry = async (entryData) => {
    setLoading(true);
    try {
      const currentEntries = await fetchTimeline();
      const newEntry = {
        id: uuidv4(),
        created_at: new Date().toISOString(),
        ...entryData
      };

      const updatedEntries = [...currentEntries, newEntry];
      
      const { error } = await supabase
        .from('violations')
        .update({ timeline_entries: updatedEntries, updated_at: new Date().toISOString() })
        .eq('id', violationId);

      if (error) throw error;

      toast({ title: "Timeline Updated", description: "New entry added successfully." });
      if (onUpdate) onUpdate();
      return true;
    } catch (error) {
      console.error('Error adding timeline entry:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to add timeline entry." });
      return false;
    } finally {
      setLoading(false);
    }
  };

  const updateEntry = async (entryId, updates) => {
    setLoading(true);
    try {
      const currentEntries = await fetchTimeline();
      const updatedEntries = currentEntries.map(entry => 
        entry.id === entryId ? { ...entry, ...updates } : entry
      );

      const { error } = await supabase
        .from('violations')
        .update({ timeline_entries: updatedEntries, updated_at: new Date().toISOString() })
        .eq('id', violationId);

      if (error) throw error;

      toast({ title: "Timeline Updated", description: "Entry updated successfully." });
      if (onUpdate) onUpdate();
      return true;
    } catch (error) {
      console.error('Error updating timeline entry:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to update entry." });
      return false;
    } finally {
      setLoading(false);
    }
  };

  const deleteEntry = async (entryId) => {
    setLoading(true);
    try {
      const currentEntries = await fetchTimeline();
      const updatedEntries = currentEntries.filter(entry => entry.id !== entryId);

      const { error } = await supabase
        .from('violations')
        .update({ timeline_entries: updatedEntries, updated_at: new Date().toISOString() })
        .eq('id', violationId);

      if (error) throw error;

      toast({ title: "Entry Deleted", description: "Timeline entry removed." });
      if (onUpdate) onUpdate();
      return true;
    } catch (error) {
      console.error('Error deleting timeline entry:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to delete entry." });
      return false;
    } finally {
      setLoading(false);
    }
  };

  return { fetchTimeline, addEntry, updateEntry, deleteEntry, loading };
};
