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

export function useVendors() {
  const [vendors, setVendors] = useState([]);
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const fetchVendors = useCallback(async (clientId = null) => {
    setLoading(true);
    try {
      let query = supabase.from('vendors').select('*').order('vendor_name', { ascending: true });
      if (clientId) {
        query = query.eq('client_id', clientId);
      }
      const { data, error } = await query;
      if (error) throw error;
      setVendors(data || []);
      return data;
    } catch (err) {
      console.error('Error fetching vendors:', err);
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to load vendors.' });
      return [];
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const addVendor = async (vendorData) => {
    try {
      const { data, error } = await supabase
        .from('vendors')
        .insert([{
          ...vendorData,
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        }])
        .select()
        .single();
        
      if (error) throw error;
      setVendors(prev => [...prev, data].sort((a, b) => a.vendor_name.localeCompare(b.vendor_name)));
      return data;
    } catch (err) {
      console.error('Error adding vendor:', err);
      toast({ variant: 'destructive', title: 'Error', description: err.message });
      return null;
    }
  };

  const updateVendor = async (id, vendorData) => {
    try {
      const { data, error } = await supabase
        .from('vendors')
        .update({
          ...vendorData,
          updated_at: new Date().toISOString()
        })
        .eq('id', id)
        .select()
        .single();
        
      if (error) throw error;
      setVendors(prev => prev.map(v => v.id === id ? data : v));
      toast({ title: 'Success', description: 'Vendor updated successfully.' });
      return data;
    } catch (err) {
      console.error('Error updating vendor:', err);
      toast({ variant: 'destructive', title: 'Error', description: err.message });
      return null;
    }
  };

  const deleteVendor = async (id) => {
    try {
      const { error } = await supabase.from('vendors').delete().eq('id', id);
      if (error) throw error;
      setVendors(prev => prev.filter(v => v.id !== id));
      toast({ title: 'Success', description: 'Vendor deleted successfully.' });
      return true;
    } catch (err) {
      console.error('Error deleting vendor:', err);
      toast({ variant: 'destructive', title: 'Error', description: err.message });
      return false;
    }
  };

  const parseCSVFile = (file, defaultClientId) => {
    return new Promise((resolve, reject) => {
      Papa.parse(file, {
        header: true,
        skipEmptyLines: true,
        complete: (results) => {
          const parsed = results.data.map(row => ({
            vendor_name: row.vendor_name?.trim() || '',
            service_type: row.service_type?.trim() || '',
            mailing_address: row.mailing_address?.trim() || '',
            email: row.email?.trim() || null,
            phone: row.phone?.trim() || row.phone_number?.trim() || null,
            phone_number: row.phone_number?.trim() || row.phone?.trim() || null,
            contact_person: row.contact_person?.trim() || '',
            tax_ein: row.tax_ein?.trim() || '',
            insurance_information: row.insurance_information?.trim() || '',
            is_1099_eligible: ['true', 'yes', '1', 'y'].includes(row.is_1099_eligible?.toLowerCase()?.trim()),
            payment_frequency: row.payment_frequency?.trim() || null,
            payment_amount: row.payment_amount ? parseFloat(row.payment_amount) : 0,
            notes: row.notes?.trim() || '',
            client_id: defaultClientId || null
          })).filter(v => v.vendor_name);
          resolve(parsed);
        },
        error: (error) => {
          reject(error);
        }
      });
    });
  };

  return {
    vendors,
    loading,
    fetchVendors,
    addVendor,
    updateVendor,
    deleteVendor,
    parseCSVFile
  };
}
