import { useState } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { validateTimelineEntry } from '@/lib/violationUtils';
import { v4 as uuidv4 } from 'uuid';

export const useViolationTimelineImport = (onSuccess) => {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [importErrors, setImportErrors] = useState([]);

  const saveEntries = async (violationId, entries) => {
    if (!violationId) {
      toast({ variant: "destructive", title: "Error", description: "No violation selected." });
      return false;
    }

    if (!entries || entries.length === 0) {
      toast({ variant: "destructive", title: "Error", description: "No entries to import." });
      return false;
    }

    setLoading(true);
    setImportErrors([]);

    try {
      const errors = [];
      const validatedEntries = entries.map((entry, index) => {
        const entryErrors = validateTimelineEntry(entry);
        if (entryErrors.length > 0) {
          errors.push({ index, message: entryErrors.join(' ') });
        }
        return {
          id: uuidv4(),
          created_at: new Date().toISOString(),
          date: new Date(entry.entry_date).toISOString(),
          status: entry.status.toLowerCase(),
          description: entry.description,
          recorded_by_name: entry.recorded_by_name,
          is_imported: true,
          created_by: {
             email: entry.recorded_by_name,
             role: 'imported' 
          }
        };
      });

      if (errors.length > 0) {
        setImportErrors(errors);
        toast({ 
          variant: "destructive", 
          title: "Validation Failed", 
          description: `Found ${errors.length} errors in your data. Please fix them before importing.` 
        });
        setLoading(false);
        return false;
      }

      const { data: violation, error: fetchError } = await supabase
        .from('violations')
        .select('timeline_entries')
        .eq('id', violationId)
        .single();

      if (fetchError) throw fetchError;

      const currentEntries = violation.timeline_entries || [];
      const newTimeline = [...currentEntries, ...validatedEntries];

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

      if (updateError) throw updateError;

      toast({ 
        title: "Import Successful", 
        description: `Successfully imported ${validatedEntries.length} timeline entries.` 
      });
      
      if (onSuccess) onSuccess();
      return true;

    } catch (error) {
      console.error('Import error:', error);
      toast({ variant: "destructive", title: "Import Failed", description: error.message || "An unexpected error occurred." });
      return false;
    } finally {
      setLoading(false);
    }
  };

  return {
    saveEntries,
    loading,
    importErrors
  };
};
