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

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

  const getClientTaskRequests = async (associationId) => {
    if (!associationId) return [];
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('client_requests')
        .select('*')
        .eq('association_id', associationId)
        .order('created_at', { ascending: false });
      if (error) throw error;
      return data || [];
    } catch (error) {
      console.error('Error fetching task requests:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to load task requests." });
      return [];
    } finally {
      setLoading(false);
    }
  };

  const getAdminTaskRequests = async () => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('client_requests')
        .select('*')
        .order('created_at', { ascending: false });
      if (error) throw error;
      return data || [];
    } catch (error) {
      console.error('Error fetching admin task requests:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to load task requests." });
      return [];
    } finally {
      setLoading(false);
    }
  };

  const createTaskRequest = async (requestData) => {
    setLoading(true);
    try {
      const { data: userData } = await supabase.auth.getUser();
      const { data: associations } = await supabase.from('associations').select('id').limit(1);
      if (!associations?.length) throw new Error('No association found');

      const { error } = await supabase.from('client_requests').insert([{
        title: requestData.title,
        description: requestData.description,
        priority: requestData.priority,
        association_id: associations[0].id,
        status: 'open',
        requester_email: userData?.user?.email,
        requester_name: userData?.user?.user_metadata?.full_name || userData?.user?.email
      }]);
      if (error) throw error;
      toast({ title: "Request Submitted", description: "Your task request has been sent for review." });
      return true;
    } catch (error) {
      console.error('Error creating task request:', error);
      toast({ variant: "destructive", title: "Error", description: error.message });
      return false;
    } finally {
      setLoading(false);
    }
  };

  const approveTaskRequest = async (requestId, adminNotes) => {
    setLoading(true);
    try {
      const { error } = await supabase
        .from('client_requests')
        .update({ status: 'resolved', description: adminNotes ? `Approved: ${adminNotes}` : undefined })
        .eq('id', requestId);
      if (error) throw error;
      toast({ title: "Request Approved", description: "Task has been approved." });
      return true;
    } catch (error) {
      console.error('Error approving request:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to approve request." });
      return false;
    } finally {
      setLoading(false);
    }
  };

  const rejectTaskRequest = async (requestId, reason) => {
    setLoading(true);
    try {
      const { error } = await supabase
        .from('client_requests')
        .update({ status: 'closed' })
        .eq('id', requestId);
      if (error) throw error;
      toast({ title: "Request Rejected", description: "The request has been rejected." });
      return true;
    } catch (error) {
      console.error('Error rejecting request:', error);
      toast({ variant: "destructive", title: "Error", description: "Failed to reject request." });
      return false;
    } finally {
      setLoading(false);
    }
  };

  return { getClientTaskRequests, getAdminTaskRequests, createTaskRequest, approveTaskRequest, rejectTaskRequest, loading };
}
