import "../styles/WeatherWidget.css";
import { useState, useEffect, useRef } from "react";
import { observer } from "mobx-react-lite";
import weatherApi from "../api/weather/weather.api";

import getWeatherIcon from "../utils/getWeatherIcon";
import windIcon from "../assets/weather-icons/wind.png";
import humidityIcon from "../assets/weather-icons/humidity.png";
import { useGeolocationStore } from "../stores";
import { translateWeatherStatus } from "../utils/translateWeatherStatus";

function WeatherDataLine({ icon, value, unit }) {
  return (
    <div className="weather-widget-data-line">
      <img src={icon} className="weather-small-icon" alt="Weather icon" />
      <div className="weather-widget-data-value">
        {unit ? (
          <>
            <span className="weather-bold-text">{value}</span>
            {unit}
          </>
        ) : (
          value
        )}
      </div>
    </div>
  );
}

const WeatherWidget = observer(() => {
  const [currentTime, setCurrentTime] = useState(new Date());
  const [weather, setWeather] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [hasLoadedOnce, setHasLoadedOnce] = useState(false);
  const lastDateRef = useRef(() => {
    const today = new Date();
    return `${today.getFullYear()}-${today.getMonth()}-${today.getDate()}`;
  });

  const store = useGeolocationStore();
  const { selectedLanguage, setError: setErrorStore } = store;

  const fetchWeather = async () => {
    try {
      const data = await weatherApi.getFormattedWeather();
      setWeather(data);
      setError(null);
      setHasLoadedOnce(true);
    } catch (err) {
      setError(err.message);
      setErrorStore(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchWeather();
  }, []);

  useEffect(() => {
    const timer = setInterval(() => {
      const now = new Date();
      setCurrentTime(now);

      const newDate = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}`;
      if (newDate !== lastDateRef.current) {
        lastDateRef.current = newDate;

        fetchWeather();
      }
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  useEffect(() => {
    const intervalId = setInterval(
      () => {
        fetchWeather();
      },
      5 * 60 * 1000,
    );

    return () => clearInterval(intervalId);
  }, [setErrorStore]);

  const formattedTime = currentTime.toLocaleTimeString(
    selectedLanguage === "ru"
      ? "ru-RU"
      : selectedLanguage === "zh"
        ? "zh-ZH"
        : "en-GB",
    { hour: "2-digit", minute: "2-digit" },
  );
  const day = currentTime.getDate().toString().padStart(2, "0");
  const month = (currentTime.getMonth() + 1).toString().padStart(2, "0");
  const weekday = currentTime.toLocaleDateString(
    selectedLanguage === "ru"
      ? "ru-RU"
      : selectedLanguage === "zh"
        ? "zh-ZH"
        : "en-GB",
    { weekday: "long" },
  );
  const formattedDate = `${day}.${month}, ${weekday}`;

  const formatDayOfWeek = (daysToAdd) => {
    const date = new Date();
    date.setDate(date.getDate() + daysToAdd);
    const dayName = date.toLocaleDateString(
      selectedLanguage === "ru"
        ? "ru-RU"
        : selectedLanguage === "zh"
          ? "zh-ZH"
          : "en-US",
      { weekday: "short" },
    );
    return dayName.charAt(0).toUpperCase() + dayName.slice(1);
  };

  if (!hasLoadedOnce) {
    return null;
  }

  if (!weather) {
    return null;
  }

  return (
    <div className="weather-widget">
      <div className="weather-widget-time">{formattedTime}</div>
      <div className="weather-widget-date">{formattedDate}</div>
      <div className="weather-widget-line"></div>
      <div className="weather-widget-content">
        <div className="weather-widget-visual">
          <img
            className="weather-icon"
            src={getWeatherIcon(weather.today.status)}
            alt="Weather condition"
          />
          <div className="weather-widget-temp">
            {weather.today.temperature}°
          </div>
          <div className="weather-widget-temp-state">
            {translateWeatherStatus(weather.today.status, selectedLanguage)}
          </div>
        </div>
        <div className="weather-widget-data">
          {weather.tomorrow.temperature !== "N/A" && (
            <WeatherDataLine
              icon={getWeatherIcon(weather.tomorrow.status)}
              value={`${formatDayOfWeek(1)} ${weather.tomorrow.temperature}°`}
            />
          )}
          {weather.dayAfterTomorrow.temperature !== "N/A" && (
            <WeatherDataLine
              icon={getWeatherIcon(weather.dayAfterTomorrow.status)}
              value={`${formatDayOfWeek(2)} ${
                weather.dayAfterTomorrow.temperature
              }°`}
            />
          )}
          <div className="weather-widget-line"></div>
          <WeatherDataLine
            icon={humidityIcon}
            value={weather.today.precipitation}
            unit="%"
          />
          <WeatherDataLine
            icon={windIcon}
            value={
              selectedLanguage === "en"
                ? (weather.today.windSpeed * 2.23694).toFixed(1)
                : weather.today.windSpeed
            }
            unit={
              selectedLanguage === "en"
                ? " mph"
                : selectedLanguage === "zh"
                  ? " 米/秒"
                  : " м/с"
            }
          />
        </div>
      </div>
    </div>
  );
});

export default WeatherWidget;
