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

export function useChecklistTimeline(checklistId) {
  const [timeline, setTimeline] = useState([]);
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const fetchTimeline = useCallback(async () => {
    if (!checklistId) return;
    try {
      setLoading(true);
      // Timeline entries stored as JSONB in checklists.items or a separate approach
      // For now, fetch checklist and extract timeline from items
      const { data, error } = await supabase
        .from('checklists')
        .select('items')
        .eq('id', checklistId)
        .single();
      if (error) throw error;
      const items = Array.isArray(data?.items) ? data.items : [];
      setTimeline(items.filter(i => i.completed_at).sort((a, b) => new Date(b.completed_at) - new Date(a.completed_at)));
    } catch (error) {
      console.error('Error fetching timeline:', error);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to load checklist timeline.' });
    } finally {
      setLoading(false);
    }
  }, [checklistId, toast]);

  const logCompletion = async (itemText, completedAt = new Date()) => {
    if (!checklistId) return;
    try {
      const { data: userData } = await supabase.auth.getUser();
      const userName = userData?.user?.email || 'Unknown';
      
      // Fetch current items, add completion, update
      const { data, error } = await supabase
        .from('checklists')
        .select('items')
        .eq('id', checklistId)
        .single();
      if (error) throw error;

      const items = Array.isArray(data?.items) ? data.items : [];
      const updatedItems = items.map(item => 
        item.text === itemText ? { ...item, completed_at: completedAt.toISOString(), completed_by: userName } : item
      );

      await supabase.from('checklists').update({ items: updatedItems }).eq('id', checklistId);
      await fetchTimeline();
    } catch (error) {
      console.error('Error logging completion:', error);
    }
  };

  const deleteEntry = async (entryId) => {
    try {
      // Remove completion from items
      const { data, error } = await supabase
        .from('checklists')
        .select('items')
        .eq('id', checklistId)
        .single();
      if (error) throw error;

      const items = Array.isArray(data?.items) ? data.items : [];
      const updatedItems = items.map(item => 
        item.id === entryId ? { ...item, completed_at: null, completed_by: null } : item
      );

      await supabase.from('checklists').update({ items: updatedItems }).eq('id', checklistId);
      setTimeline(prev => prev.filter(item => item.id !== entryId));
      toast({ title: 'Success', description: 'Timeline entry removed.' });
    } catch (error) {
      console.error('Error deleting entry:', error);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to delete entry.' });
    }
  };

  return { timeline, loading, fetchTimeline, logCompletion, deleteEntry };
}
