import { useState, useCallback } from "react";
import axios from "axios";
import { toast } from "sonner";
import { useNavigate } from "react-router-dom";

const API = `${process.env.REACT_APP_BACKEND_URL}/api`;

/**
 * Custom hook for admin API calls with consistent error handling
 * @param {string} token - Auth token
 * @returns {Object} API methods and loading state
 */
export const useAdminAPI = (token) => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const handleError = useCallback(
    (error, defaultMessage = "Operation failed") => {
      console.error(defaultMessage, error);

      if (error.response) {
        const { status } = error.response;
        if (status === 401) {
          toast.error("Session expired. Please login again.");
          navigate("/login");
        } else if (status === 403) {
          toast.error("Admin access required");
          navigate("/");
        } else if (status === 500) {
          toast.error("Server error. Please try again later.");
        } else {
          toast.error(`${defaultMessage} (Error ${status})`);
        }
      } else if (error.request) {
        toast.error("Cannot connect to server. Please check your connection.");
      } else {
        toast.error(defaultMessage);
      }
    },
    [navigate]
  );

  const getHeaders = useCallback(
    () => ({
      Authorization: `Bearer ${token}`,
    }),
    [token]
  );

  const apiGet = useCallback(
    async (endpoint, errorMessage) => {
      try {
        setLoading(true);
        const response = await axios.get(`${API}${endpoint}`, {
          headers: getHeaders(),
          timeout: 10000,
        });
        return response.data;
      } catch (error) {
        handleError(error, errorMessage);
        throw error;
      } finally {
        setLoading(false);
      }
    },
    [token, getHeaders, handleError]
  );

  const apiPost = useCallback(
    async (endpoint, data, errorMessage) => {
      try {
        setLoading(true);
        const response = await axios.post(`${API}${endpoint}`, data, {
          headers: getHeaders(),
          timeout: 10000,
        });
        return response.data;
      } catch (error) {
        handleError(error, errorMessage);
        throw error;
      } finally {
        setLoading(false);
      }
    },
    [token, getHeaders, handleError]
  );

  const apiPut = useCallback(
    async (endpoint, data, errorMessage) => {
      try {
        setLoading(true);
        const response = await axios.put(`${API}${endpoint}`, data, {
          headers: getHeaders(),
          timeout: 10000,
        });
        return response.data;
      } catch (error) {
        handleError(error, errorMessage);
        throw error;
      } finally {
        setLoading(false);
      }
    },
    [token, getHeaders, handleError]
  );

  const apiDelete = useCallback(
    async (endpoint, errorMessage) => {
      try {
        setLoading(true);
        const response = await axios.delete(`${API}${endpoint}`, {
          headers: getHeaders(),
          timeout: 10000,
        });
        return response.data;
      } catch (error) {
        handleError(error, errorMessage);
        throw error;
      } finally {
        setLoading(false);
      }
    },
    [token, getHeaders, handleError]
  );

  return {
    loading,
    apiGet,
    apiPost,
    apiPut,
    apiDelete,
  };
};
