import { weatherInstance } from "../apiConfig";

const WEATHER_STATUS_MAP = {
  Rain: "дождливо",
  Clouds: "облачно",
  Clear: "солнечно",
  Thunderstorm: "гроза",
  Snow: "снег",
  Drizzle: "мелкий дождь",
  Fog: "туман",
};

export default {
  async getFormattedWeather(lat = 59.938784, lng = 30.314997) {
    try {
      const response = await weatherInstance.post("/v1/weather", {
        coordinates: { latitude: lat, longitude: lng },
      });

      return this._formatWeatherData(response.data);
    } catch (error) {
      console.error("Weather API error:", error);
      throw new Error("Не удалось получить данные о погоде");
    }
  },

  _formatWeatherData(data) {
    const today = new Date();
    const tomorrow = new Date();
    const dayAfterTomorrow = new Date();
    tomorrow.setDate(today.getDate() + 1);
    dayAfterTomorrow.setDate(today.getDate() + 2);

    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    };

    const tomorrowDateStr = formatDate(tomorrow);
    const dayAfterTomorrowDateStr = formatDate(dayAfterTomorrow);

    const todayForecast = data.currentWeather;

    const tomorrowForecast = (data.forecast || []).find((item) => {
      if (!item || !item.date) return false;

      const itemDateStr = item.date;
      return itemDateStr === tomorrowDateStr;
    });

    const dayAfterTomorrowForecast = (data.forecast || []).find((item) => {
      if (!item || !item.date) return false;

      const itemDateStr = item.date;
      return itemDateStr === dayAfterTomorrowDateStr;
    });

    const getTemperature = (forecast) => {
      if (!forecast) return "N/A";

      if (
        forecast.minTemperatureCelsius != null &&
        forecast.maxTemperatureCelsius != null
      ) {
        const max = Math.round(forecast.maxTemperatureCelsius);
        const min = Math.round(forecast.minTemperatureCelsius);

        return `${max} / ${min}`;
      }

      if (forecast.minTemperatureCelsius != null) {
        return Math.round(forecast.minTemperatureCelsius);
      }

      if (forecast.maxTemperatureCelsius != null) {
        return Math.round(forecast.maxTemperatureCelsius);
      }

      if (forecast.temperatureCelsius != null) {
        return Math.round(forecast.temperatureCelsius);
      }

      return "N/A";
    };

    return {
      today: {
        temperature: todayForecast ? getTemperature(todayForecast) : "N/A",
        status:
          todayForecast && todayForecast.description
            ? WEATHER_STATUS_MAP[todayForecast.description] ||
              todayForecast.description
            : "данные отсутствуют",
        precipitation:
          todayForecast && todayForecast.humidity != null
            ? todayForecast.humidity
            : "N/A",
        windSpeed:
          todayForecast && todayForecast.windSpeed != null
            ? todayForecast.windSpeed
            : "N/A",
      },
      tomorrow: {
        temperature: getTemperature(tomorrowForecast),
        status:
          tomorrowForecast && tomorrowForecast.description
            ? WEATHER_STATUS_MAP[tomorrowForecast.description] ||
              tomorrowForecast.description
            : "данные отсутствуют",
        precipitation:
          tomorrowForecast && tomorrowForecast.humidity != null
            ? tomorrowForecast.humidity
            : "N/A",
        windSpeed:
          tomorrowForecast && tomorrowForecast.windSpeed != null
            ? tomorrowForecast.windSpeed
            : "N/A",
      },
      dayAfterTomorrow: {
        temperature: getTemperature(dayAfterTomorrowForecast),
        status:
          dayAfterTomorrowForecast && dayAfterTomorrowForecast.description
            ? WEATHER_STATUS_MAP[dayAfterTomorrowForecast.description] ||
              dayAfterTomorrowForecast.description
            : "данные отсутствуют",
        precipitation:
          dayAfterTomorrowForecast && dayAfterTomorrowForecast.humidity != null
            ? dayAfterTomorrowForecast.humidity
            : "N/A",
        windSpeed:
          dayAfterTomorrowForecast && dayAfterTomorrowForecast.windSpeed != null
            ? dayAfterTomorrowForecast.windSpeed
            : "N/A",
      },
    };
  },
};
