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

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

  const getMyRequests = useCallback(async () => {
    setLoading(true);
    try {
      const { data: userData } = await supabase.auth.getUser();
      if (!userData?.user) return [];

      const { data, error } = await supabase
        .from('client_requests')
        .select('*')
        .eq('requester_email', userData.user.email)
        .order('created_at', { ascending: false });

      if (error) throw error;
      return data || [];
    } catch (error) {
      console.error('[useClientDateRequests] Error fetching requests:', error);
      toast({ title: 'Error', description: 'Failed to load your requests', variant: 'destructive' });
      return [];
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const submitDateRequest = useCallback(async (date, description) => {
    if (!date) {
      toast({ variant: 'destructive', title: 'Error', description: 'Invalid date selected' });
      return false;
    }

    setLoading(true);
    try {
      const { data: userData } = await supabase.auth.getUser();
      if (!userData?.user) throw new Error('Not authenticated');

      const { data: associations } = await supabase.from('associations').select('id').limit(1);
      if (!associations?.length) throw new Error('No association found');

      const payload = {
        association_id: associations[0].id,
        title: `Date Request: ${date}`,
        description: description,
        status: 'open',
        requester_email: userData.user.email,
        requester_name: userData.user.user_metadata?.full_name || userData.user.email
      };

      const { error: insertError } = await supabase.from('client_requests').insert([payload]);
      if (insertError) throw insertError;

      toast({ title: 'Request Submitted', description: 'Your date request has been sent for approval.' });
      return true;
    } catch (error) {
      console.error('[useClientDateRequests] Submit error:', error);
      toast({ variant: 'destructive', title: 'Submission Failed', description: error.message || 'An error occurred.' });
      return false;
    } finally {
      setLoading(false);
    }
  }, [toast]);

  const deleteDateRequest = async (id) => {
    setLoading(true);
    try {
      const { error } = await supabase.from('client_requests').delete().eq('id', id);
      if (error) throw error;
      toast({ title: 'Success', description: 'Request cancelled' });
      return true;
    } catch (error) {
      console.error('[useClientDateRequests] Error deleting request:', error);
      toast({ title: 'Error', description: 'Failed to cancel request', variant: 'destructive' });
      return false;
    } finally {
      setLoading(false);
    }
  };

  return { getMyRequests, submitDateRequest, deleteDateRequest, loading };
}
