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

export function usePropertyAssignment() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const { toast } = useToast();

  const fetchAssociations = useCallback(async () => {
    try {
      setLoading(true);
      const { data, error } = await supabase
        .from('clients')
        .select('id, name')
        .order('name');
      
      if (error) throw error;
      return data;
    } catch (err) {
      console.error('Error fetching associations:', err);
      setError(err.message);
      return [];
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchProperties = useCallback(async (clientId) => {
    try {
      setLoading(true);
      let query = supabase
        .from('property_owners')
        .select('id, owner_name, property_address')
        .order('owner_name');
        
      if (clientId) {
        query = query.eq('client_id', clientId);
      }
      
      const { data, error } = await query;
      
      if (error) throw error;
      return data;
    } catch (err) {
      console.error('Error fetching properties:', err);
      setError(err.message);
      return [];
    } finally {
      setLoading(false);
    }
  }, []);

  const updateTaskProperty = useCallback(async (taskId, propertyId) => {
    try {
      setLoading(true);
      const { error } = await supabase
        .from('tasks')
        .update({ property_id: propertyId })
        .eq('id', taskId);

      if (error) throw error;

      toast({
        title: "Property Updated",
        description: "Task property assignment saved successfully.",
      });
      return true;
    } catch (err) {
      console.error('Error updating task property:', err);
      toast({
        variant: "destructive",
        title: "Update Failed",
        description: "Could not update property assignment.",
      });
      return false;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const updateTaskAssociation = useCallback(async (taskId, clientId) => {
    try {
      setLoading(true);
      const { error } = await supabase
        .from('tasks')
        .update({ client_id: clientId })
        .eq('id', taskId);

      if (error) throw error;

      toast({
        title: "Association Updated",
        description: "Task association assignment saved successfully.",
      });
      return true;
    } catch (err) {
      console.error('Error updating task association:', err);
      toast({
        variant: "destructive",
        title: "Update Failed",
        description: "Could not update association assignment.",
      });
      return false;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  return {
    loading,
    error,
    fetchAssociations,
    fetchProperties,
    updateTaskProperty,
    updateTaskAssociation
  };
}
