import React, { useEffect, useState } from "react";
import { fetchWeatherByCity, fetchWeatherByPostId, fetchWeatherByCoords } from "../../api/client";
import "./WeatherModal.css";

const weatherIcons = {
  sun: "\u2600\ufe0f",
  moon: "\ud83c\udf19",
  "cloud-sun": "\u26c5",
  "cloud-moon": "\u2601\ufe0f",
  cloud: "\u2601\ufe0f",
  smog: "\ud83c\udf2b\ufe0f",
  "cloud-rain": "\ud83c\udf27\ufe0f",
  "cloud-showers-heavy": "\ud83c\udf27\ufe0f",
  snowflake: "\u2744\ufe0f",
  "cloud-sun-rain": "\ud83c\udf26\ufe0f",
  "cloud-meatball": "\ud83c\udf28\ufe0f",
  bolt: "\u26c8\ufe0f",
  "temperature-half": "\ud83c\udf21\ufe0f"
};

function getWeatherEmoji(iconName) {
  return weatherIcons[iconName] || "\ud83c\udf21\ufe0f";
}

function getDayName(dateStr) {
  const date = new Date(dateStr);
  const today = new Date();
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1);

  if (date.toDateString() === today.toDateString()) return "Today";
  if (date.toDateString() === tomorrow.toDateString()) return "Tomorrow";

  return date.toLocaleDateString("en-US", { weekday: "short" });
}

function formatHour(timeStr) {
  const date = new Date(timeStr);
  return date.toLocaleTimeString("en-US", { hour: "numeric", hour12: true });
}

export default function WeatherModal({ postId, city, lat, lon, onClose }) {
  const [weather, setWeather] = useState(null);
  const [loading, setLoading] = useState(true);
  const [tab, setTab] = useState("hourly");

  useEffect(() => {
    async function load() {
      setLoading(true);
      let data = null;

      if (postId) {
        data = await fetchWeatherByPostId(postId);
      } else if (city) {
        data = await fetchWeatherByCity(city);
      } else if (lat !== undefined && lon !== undefined) {
        data = await fetchWeatherByCoords(lat, lon);
      }

      setWeather(data);
      setLoading(false);
    }
    load();
  }, [postId, city, lat, lon]);

  const handleBackdropClick = (e) => {
    if (e.target.classList.contains("weather-modal-backdrop")) {
      onClose();
    }
  };

  if (loading) {
    return (
      <div className="weather-modal-backdrop" onClick={handleBackdropClick}>
        <div className="weather-modal weather-modal--loading">
          <div className="weather-loading-spinner" />
        </div>
      </div>
    );
  }

  if (!weather) {
    return (
      <div className="weather-modal-backdrop" onClick={handleBackdropClick}>
        <div className="weather-modal weather-modal--error">
          <p>Weather data unavailable</p>
          <button onClick={onClose}>Close</button>
        </div>
      </div>
    );
  }

  const current = weather.current || {};

  return (
    <div className="weather-modal-backdrop" onClick={handleBackdropClick}>
      <div className="weather-modal">
        <button className="weather-modal-close" onClick={onClose}>
          &times;
        </button>

        <header className="weather-modal-header">
          <h2>{weather.city}</h2>
          <span className="weather-modal-country">{weather.country}</span>
        </header>

        <section className="weather-current">
          <div className="weather-current-icon">
            {getWeatherEmoji(current.weather_icon)}
          </div>
          <div className="weather-current-temp">
            {Math.round(current.temperature)}&deg;
          </div>
          <div className="weather-current-details">
            <span className="weather-condition">{current.weather_text}</span>
            <span className="weather-feels">
              Feels like {Math.round(current.feels_like)}&deg;
            </span>
          </div>
        </section>

        <section className="weather-stats">
          <div className="weather-stat">
            <span className="weather-stat-icon">💧</span>
            <span className="weather-stat-value">{current.humidity}%</span>
            <span className="weather-stat-label">Humidity</span>
          </div>
          <div className="weather-stat">
            <span className="weather-stat-icon">🌬️</span>
            <span className="weather-stat-value">{Math.round(current.wind_speed)} km/h</span>
            <span className="weather-stat-label">Wind</span>
          </div>
          <div className="weather-stat">
            <span className="weather-stat-icon">☁️</span>
            <span className="weather-stat-value">{current.cloud_cover}%</span>
            <span className="weather-stat-label">Clouds</span>
          </div>
        </section>

        <nav className="weather-tabs">
          <button
            className={tab === "hourly" ? "active" : ""}
            onClick={() => setTab("hourly")}
          >
            24 Hours
          </button>
          <button
            className={tab === "daily" ? "active" : ""}
            onClick={() => setTab("daily")}
          >
            7 Days
          </button>
        </nav>

        {tab === "hourly" && weather.hourly && (
          <section className="weather-hourly">
            {weather.hourly.slice(0, 24).map((h, i) => (
              <div key={i} className="weather-hourly-item">
                <span className="weather-hourly-time">{formatHour(h.time)}</span>
                <span className="weather-hourly-icon">
                  {h.weather_code === 0 ? "\u2600\ufe0f" : h.weather_code <= 3 ? "\u26c5" : h.weather_code <= 48 ? "\ud83c\udf2b\ufe0f" : h.weather_code <= 67 ? "\ud83c\udf27\ufe0f" : "\u2744\ufe0f"}
                </span>
                <span className="weather-hourly-temp">{Math.round(h.temperature)}&deg;</span>
              </div>
            ))}
          </section>
        )}

        {tab === "daily" && weather.daily && (
          <section className="weather-daily">
            {weather.daily.map((d, i) => (
              <div key={i} className="weather-daily-item">
                <span className="weather-daily-day">{getDayName(d.date)}</span>
                <span className="weather-daily-icon">
                  {d.weather_code === 0 ? "\u2600\ufe0f" : d.weather_code <= 3 ? "\u26c5" : d.weather_code <= 48 ? "\ud83c\udf2b\ufe0f" : d.weather_code <= 67 ? "\ud83c\udf27\ufe0f" : "\u2744\ufe0f"}
                </span>
                <span className="weather-daily-temps">
                  <span className="weather-daily-high">{Math.round(d.temp_max)}&deg;</span>
                  <span className="weather-daily-low">{Math.round(d.temp_min)}&deg;</span>
                </span>
                <span className="weather-daily-precip">
                  {d.precipitation_sum > 0 && `\ud83d\udca7 ${d.precipitation_sum.toFixed(1)}mm`}
                </span>
              </div>
            ))}
          </section>
        )}

        <footer className="weather-modal-footer">
          <span>Data: Open-Meteo</span>
        </footer>
      </div>
    </div>
  );
}
