import { useState, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';

export const useIndividualOwners = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchOwnersByAssociation = useCallback(async (associationId) => {
    if (!associationId) return [];
    setLoading(true);
    setError(null);
    try {
      const { data, error: fetchError } = await supabase
        .from('owners')
        .select('*')
        .eq('association_id', associationId)
        .eq('status', 'active')
        .order('last_name');

      if (fetchError) throw fetchError;
      return data || [];
    } catch (err) {
      console.error("Error fetching owners:", err);
      setError(err.message);
      return [];
    } finally {
      setLoading(false);
    }
  }, []);

  const addOwner = useCallback(async (ownerData) => {
    setLoading(true);
    setError(null);
    try {
      const { data, error: insertError } = await supabase
        .from('owners')
        .insert([ownerData])
        .select()
        .single();

      if (insertError) throw insertError;
      return data;
    } catch (err) {
      console.error("Error adding owner:", err);
      setError(err.message);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const updateOwner = useCallback(async (id, updates) => {
    setLoading(true);
    setError(null);
    try {
      const { data, error: updateError } = await supabase
        .from('owners')
        .update({ ...updates, updated_at: new Date().toISOString() })
        .eq('id', id)
        .select()
        .single();

      if (updateError) throw updateError;
      return data;
    } catch (err) {
      console.error("Error updating owner:", err);
      setError(err.message);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const deleteOwner = useCallback(async (id) => {
    setLoading(true);
    setError(null);
    try {
      const { error: deleteError } = await supabase
        .from('owners')
        .delete()
        .eq('id', id);

      if (deleteError) throw deleteError;
      return true;
    } catch (err) {
      console.error("Error deleting owner:", err);
      setError(err.message);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  const bulkUploadOwners = useCallback(async (owners) => {
    setLoading(true);
    setError(null);
    try {
      const chunkSize = 100;
      for (let i = 0; i < owners.length; i += chunkSize) {
        const chunk = owners.slice(i, i + chunkSize);
        const { error: insertError } = await supabase
          .from('owners')
          .insert(chunk);
        if (insertError) throw insertError;
      }
      return true;
    } catch (err) {
      console.error("Error bulk uploading owners:", err);
      setError(err.message);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  return { loading, error, fetchOwnersByAssociation, addOwner, updateOwner, deleteOwner, bulkUploadOwners };
};
