import { useState, useCallback } from 'react';
import { useToast } from '@/components/ui/ToastContext';
import { ApiClient, ApiError, ApiResponse } from '@/lib/api-utils';

interface UseApiCallOptions {
  showSuccessToast?: boolean;
  showErrorToast?: boolean;
  successMessage?: string;
  errorTitle?: string;
}

interface UseApiCallState<T> {
  data: T | null;
  loading: boolean;
  error: ApiError | null;
}

export function useApiCall<T = any>(options: UseApiCallOptions = {}) {
  const { showSuccessToast = false, showErrorToast = true, successMessage, errorTitle } = options;
  const { showSuccess, showError } = useToast();
  
  const [state, setState] = useState<UseApiCallState<T>>({
    data: null,
    loading: false,
    error: null,
  });

  const execute = useCallback(async (
    apiCall: () => Promise<ApiResponse<T>>
  ): Promise<T | null> => {
    setState(prev => ({ ...prev, loading: true, error: null }));

    try {
      const response = await apiCall();
      
      if (response.success) {
        setState(prev => ({ 
          ...prev, 
          data: response.data || null, 
          loading: false, 
          error: null 
        }));

        if (showSuccessToast) {
          showSuccess(
            successMessage || response.message || 'Operation completed successfully'
          );
        }

        return response.data || null;
      } else {
        throw new ApiError(response.error || 'Operation failed', 400);
      }
    } catch (error) {
      const apiError = error instanceof ApiError ? error : new ApiError(
        error instanceof Error ? error.message : 'An unexpected error occurred',
        500
      );

      setState(prev => ({ 
        ...prev, 
        data: null, 
        loading: false, 
        error: apiError 
      }));

      if (showErrorToast) {
        showError(
          apiError.getDisplayMessage(),
          errorTitle || 'Error'
        );
      }

      throw apiError;
    }
  }, [showSuccessToast, showErrorToast, successMessage, errorTitle, showSuccess, showError]);

  const reset = useCallback(() => {
    setState({
      data: null,
      loading: false,
      error: null,
    });
  }, []);

  return {
    ...state,
    execute,
    reset,
  };
}

// Specific hooks for common operations
export function useBidSubmission() {
  return useApiCall({
    showSuccessToast: true,
    showErrorToast: true,
    successMessage: 'Bid submitted successfully! Chat has been initialized.',
    errorTitle: 'Bid Submission Failed'
  });
}

export function useProjectAward() {
  return useApiCall({
    showSuccessToast: true,
    showErrorToast: true,
    successMessage: 'Project awarded successfully! Notifications sent to all bidders.',
    errorTitle: 'Project Award Failed'
  });
}

export function useProjectCancellation() {
  return useApiCall({
    showSuccessToast: true,
    showErrorToast: true,
    successMessage: 'Project cancelled successfully. All freelancers have been notified.',
    errorTitle: 'Project Cancellation Failed'
  });
}

export function useMembershipPurchase() {
  return useApiCall({
    showSuccessToast: true,
    showErrorToast: true,
    successMessage: 'Membership purchased successfully! You can now bid on projects.',
    errorTitle: 'Membership Purchase Failed'
  });
}

export function useBidUpdate() {
  return useApiCall({
    showSuccessToast: true,
    showErrorToast: true,
    successMessage: 'Bid updated successfully.',
    errorTitle: 'Bid Update Failed'
  });
}

export function useMessageSend() {
  return useApiCall({
    showSuccessToast: false, // We handle this in the component
    showErrorToast: true,
    errorTitle: 'Message Send Failed'
  });
}