import axios from "axios";

const API_URL = "http://localhost:8000/api";

export const getAuthToken = () => {
  return localStorage.getItem("token");
};

export const loginUser = async (loginData) => {
  const params = new URLSearchParams();
  params.append("grant_type", "password");
  params.append("username", loginData.login);
  params.append("password", loginData.password);

  try {
    const response = await axios.post(`${API_URL}/token`, params, {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        Accept: "application/json",
      },
    });

    return {
      token: response.data.access_token,
      user: response.data.user,
    };
  } catch (error) {
    console.log(
      "Ошибка при запросе:",
      error.response ? error.response.data : error
    );
    throw error.response ? error.response.data : error;
  }
};

export const getAccessories = async () => {
  try {
    const response = await axios.get(`${API_URL}/accessories`, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        Accept: "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при получении аксессуаров:", error);
    throw error;
  }
};

export const createAccessory = async (accessoryData) => {
  try {
    console.log(accessoryData);
    const response = await axios.post(`${API_URL}/accessories`, accessoryData, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        "Content-Type": "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при создании аксессуара:", error);
    throw error;
  }
};

export const updateAccessory = async (id, accessoryData) => {
  try {
    const response = await axios.put(
      `${API_URL}/accessories/${id}`,
      accessoryData,
      {
        headers: {
          Authorization: `Bearer ${getAuthToken()}`,
          "Content-Type": "application/json",
        },
      }
    );
    return response.data;
  } catch (error) {
    console.log("Ошибка при обновлении аксессуара:", error);
    throw error;
  }
};

export const deleteAccessory = async (id) => {
  try {
    await axios.delete(`${API_URL}/accessories/${id}`, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        Accept: "application/json",
      },
    });
  } catch (error) {
    console.log("Ошибка при удалении аксессуара:", error);
    throw error;
  }
};

export const getCities = async () => {
  try {
    const response = await axios.get(`${API_URL}/cities`, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        Accept: "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при получении городов:", error);
    throw error;
  }
};

export const createCity = async (cityData) => {
  try {
    const response = await axios.post(`${API_URL}/cities`, cityData, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        "Content-Type": "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при создании города:", error);
    throw error;
  }
};

export const updateCity = async (id, cityData) => {
  try {
    const response = await axios.put(`${API_URL}/cities/${id}`, cityData, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        "Content-Type": "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при обновлении города:", error);
    throw error;
  }
};

export const deleteCity = async (id) => {
  try {
    await axios.delete(`${API_URL}/cities/${id}`, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        Accept: "application/json",
      },
    });
  } catch (error) {
    console.log("Ошибка при удалении города:", error);
    throw error;
  }
};

export const getFederalDistricts = async () => {
  try {
    const response = await axios.get(`${API_URL}/federal-districts`, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        Accept: "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при получении федеральных округов:", error);
    throw error;
  }
};

export const createFederalDistrict = async (districtData) => {
  try {
    const response = await axios.post(
      `${API_URL}/federal-districts`,
      districtData,
      {
        headers: {
          Authorization: `Bearer ${getAuthToken()}`,
          "Content-Type": "application/json",
        },
      }
    );
    return response.data;
  } catch (error) {
    console.log("Ошибка при создании федерального округа:", error);
    throw error;
  }
};

export const updateFederalDistrict = async (id, districtData) => {
  try {
    const response = await axios.put(
      `${API_URL}/federal-districts/${id}`,
      districtData,
      {
        headers: {
          Authorization: `Bearer ${getAuthToken()}`,
          "Content-Type": "application/json",
        },
      }
    );
    return response.data;
  } catch (error) {
    console.log("Ошибка при обновлении федерального округа:", error);
    throw error;
  }
};

export const deleteFederalDistrict = async (id) => {
  try {
    await axios.delete(`${API_URL}/federal-districts/${id}`, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        Accept: "application/json",
      },
    });
  } catch (error) {
    console.log("Ошибка при удалении федерального округа:", error);
    throw error;
  }
};

export const getRoles = async () => {
  try {
    const response = await axios.get(`${API_URL}/roles`, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        Accept: "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при загрузке ролей:", error);
    throw error;
  }
};

export const createRole = async (roleData) => {
  try {
    const response = await axios.post(`${API_URL}/roles`, roleData, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        "Content-Type": "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при создании роли:", error);
    throw error;
  }
};

export const updateRole = async (id, roleData) => {
  try {
    const response = await axios.put(`${API_URL}/roles/${id}`, roleData, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        "Content-Type": "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при обновлении роли:", error);
    throw error;
  }
};

export const deleteRole = async (id) => {
  try {
    await axios.delete(`${API_URL}/roles/${id}`, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        Accept: "application/json",
      },
    });
  } catch (error) {
    console.log("Ошибка при удалении роли:", error);
    throw error;
  }
};

export const getStatuses = async () => {
  try {
    const response = await axios.get(`${API_URL}/statuses`, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        Accept: "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при загрузке статусов:", error);
    throw error;
  }
};

export const createStatus = async (statusData) => {
  try {
    const response = await axios.post(`${API_URL}/statuses`, statusData, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        "Content-Type": "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при создании статуса:", error);
    throw error;
  }
};

export const updateStatus = async (id, statusData) => {
  try {
    const response = await axios.put(`${API_URL}/statuses/${id}`, statusData, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        "Content-Type": "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при обновлении статуса:", error);
    throw error;
  }
};

export const deleteStatus = async (id) => {
  try {
    await axios.delete(`${API_URL}/statuses/${id}`, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        Accept: "application/json",
      },
    });
  } catch (error) {
    console.log("Ошибка при удалении статуса:", error);
    throw error;
  }
};

export const getTrucks = async () => {
  try {
    const response = await axios.get(`${API_URL}/trucks`, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        Accept: "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при загрузке грузовиков:", error);
    throw error;
  }
};

export const createTruck = async (truckData) => {
  try {
    const response = await axios.post(`${API_URL}/trucks`, truckData, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        "Content-Type": "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при создании грузовика:", error);
    throw error;
  }
};

export const updateTruck = async (id, truckData) => {
  try {
    const response = await axios.put(`${API_URL}/trucks/${id}`, truckData, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        "Content-Type": "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при обновлении грузовика:", error);
    throw error;
  }
};

export const deleteTruck = async (id) => {
  try {
    await axios.delete(`${API_URL}/trucks/${id}`, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        Accept: "application/json",
      },
    });
  } catch (error) {
    console.log("Ошибка при удалении грузовика:", error);
    throw error;
  }
};

export const getUsers = async () => {
  try {
    const response = await axios.get(`${API_URL}/users`, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        Accept: "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при загрузке пользователей:", error);
    throw error;
  }
};

export const createUser = async (userData) => {
  try {
    const response = await axios.post(`${API_URL}/users`, userData, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        "Content-Type": "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при создании пользователя:", error);
    throw error;
  }
};

export const updateUser = async (id, userData) => {
  try {
    const response = await axios.put(`${API_URL}/users/${id}`, userData, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        "Content-Type": "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при обновлении пользователя:", error);
    throw error;
  }
};

export const deleteUser = async (id) => {
  try {
    await axios.delete(`${API_URL}/users/${id}`, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        Accept: "application/json",
      },
    });
  } catch (error) {
    console.log("Ошибка при удалении пользователя:", error);
    throw error;
  }
};

export const getTotalOrders = async () => {
  try {
    const response = await axios.get(`${API_URL}/total-orders`, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        Accept: "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при загрузке общих заказов:", error);
    throw error;
  }
};
export const createTotalOrder = async (orderData) => {
  try {
    const response = await axios.post(`${API_URL}/total-orders`, orderData, {
      headers: {
        Authorization: `Bearer ${getAuthToken()}`,
        "Content-Type": "application/json",
      },
    });
    return response.data;
  } catch (error) {
    console.log("Ошибка при создании заказа:", error);
    throw error;
  }
};

export const getDeliveryOrders = async (totalOrderId) => {
  try {
    const response = await axios.get(
      `${API_URL}/delivery-orders/total/${totalOrderId}`,
      {
        headers: {
          Authorization: `Bearer ${getAuthToken()}`,
          Accept: "application/json",
        },
      }
    );
    return response.data;
  } catch (error) {
    console.log("Ошибка при загрузке подзаказов:", error);
    throw error;
  }
};

export const getDeliveryAccessories = async (deliveryOrderId) => {
  try {
    const response = await axios.get(
      `${API_URL}/delivery-orders/${deliveryOrderId}/accessories`,
      {
        headers: {
          Authorization: `Bearer ${getAuthToken()}`,
          Accept: "application/json",
        },
      }
    );
    return response.data;
  } catch (error) {
    console.log("Ошибка при загрузке доставок:", error);
    throw error;
  }
};

export const getDeliveryOrderDetails = async (deliveryOrderId) => {
  try {
    const response = await axios.get(
      `${API_URL}/delivery-orders/${deliveryOrderId}`,
      {
        headers: {
          Authorization: `Bearer ${getAuthToken()}`,
          Accept: "application/json",
        },
      }
    );
    return response.data;
  } catch (error) {
    console.log("Ошибка при загрузке деталей заказа доставки:", error);
    throw error;
  }
};

export const calculateTotalOrder = async (deadline, robotsCount) => {
  try {
    const response = await axios.post(
      `${API_URL}/total-orders/calculate`,
      null,
      {
        headers: {
          Authorization: `Bearer ${getAuthToken()}`,
          "Content-Type": "application/json",
        },
      }
    );
    return response.data;
  } catch (error) {
    console.log("Ошибка при запуске расчета заказа:", error);
    throw error;
  }
};

export const updateDeliveryOrderRoute = async (
  deliveryOrderId,
  estimatedRouteTime,
  route
) => {
  console.log({
    estimated_route_time_in_minutes: estimatedRouteTime,
    route: route,
  });
  try {
    const response = await axios.put(
      `${API_URL}/delivery-orders/${deliveryOrderId}/route`,
      {
        estimated_route_time_in_minutes: estimatedRouteTime,
        route: route,
      },
      {
        headers: {
          Authorization: `Bearer ${getAuthToken()}`,
          "Content-Type": "application/json",
        },
      }
    );
    return response.data;
  } catch (error) {
    console.error("Ошибка при обновлении маршрута подзаказа:", error);
    throw error;
  }
};
