import { useState, useCallback } from 'react';
import { api } from '../services/api';
import { AxiosError } from 'axios';

export interface ApiResponse<T = any> {
  success: boolean;
  message?: string;
  data?: T;
  error?: string;
}

export interface UseApiMutationResult<T, P = any> {
  mutate: (data: P) => Promise<T | null>;
  loading: boolean;
  error: string | null;
  success: boolean;
  reset: () => void;
}

/**
 * Hook for API mutations (POST, PUT, PATCH, DELETE)
 * Handles loading states, errors, and success messages
 * 
 * @example
 * const { mutate, loading, error } = useApiMutation<Article>('post', '/articles');
 * await mutate({ title: 'New Article' });
 */
export function useApiMutation<T = any, P = any>(
  method: 'post' | 'put' | 'patch' | 'delete',
  endpoint: string | ((data: P) => string)
): UseApiMutationResult<T, P> {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const mutate = useCallback(
    async (data: P): Promise<T | null> => {
      try {
        setLoading(true);
        setError(null);
        setSuccess(false);

        const url = typeof endpoint === 'function' ? endpoint(data) : endpoint;
        const response = await api[method]<ApiResponse<T>>(url, data);

        if (response.data.success !== false) {
          setSuccess(true);
          return response.data.data || (response.data as any);
        } else {
          setError(response.data.error || response.data.message || 'Operation failed');
          return null;
        }
      } catch (err) {
        const axiosError = err as AxiosError<ApiResponse>;
        const errorMsg =
          axiosError.response?.data?.error ||
          axiosError.response?.data?.message ||
          axiosError.message ||
          'An error occurred';
        setError(errorMsg);
        return null;
      } finally {
        setLoading(false);
      }
    },
    [method, endpoint]
  );

  const reset = useCallback(() => {
    setError(null);
    setSuccess(false);
  }, []);

  return {
    mutate,
    loading,
    error,
    success,
    reset,
  };
}

/**
 * Convenience hooks for specific HTTP methods
 */
export const useApiPost = <T = any, P = any>(endpoint: string | ((data: P) => string)) =>
  useApiMutation<T, P>('post', endpoint);

export const useApiPut = <T = any, P = any>(endpoint: string | ((data: P) => string)) =>
  useApiMutation<T, P>('put', endpoint);

export const useApiPatch = <T = any, P = any>(endpoint: string | ((data: P) => string)) =>
  useApiMutation<T, P>('patch', endpoint);

export const useApiDelete = <T = any, P = any>(endpoint: string | ((data: P) => string)) =>
  useApiMutation<T, P>('delete', endpoint);
