'use client'

import React, { useEffect, useState } from 'react'
import { wmoCodeToLabel, isGoodForFlying, WeatherData } from '@/lib/weather'

interface SpotWeatherCardProps {
  lat: number
  lng: number
}

function windDir(deg: number): string {
  const dirs = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']
  return dirs[Math.round(deg / 45) % 8]
}

function sunsetPortugal(): string {
  const month = new Date().getMonth()
  const sunsets = [17, 18, 19, 20, 21, 21, 21, 21, 20, 19, 17, 17]
  return `~${sunsets[month]}:00`
}

export function SpotWeatherCard({ lat, lng }: SpotWeatherCardProps) {
  const [weather, setWeather] = useState<WeatherData | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(false)

  useEffect(() => {
    fetch(`/api/weather?lat=${lat}&lng=${lng}`)
      .then((r) => r.json())
      .then((data) => {
        if (data.error) setError(true)
        else setWeather(data)
      })
      .catch(() => setError(true))
      .finally(() => setLoading(false))
  }, [lat, lng])

  const good = weather ? isGoodForFlying(weather) : null

  return (
    <>
      {loading && (
        <div className="meteo-row">
          <span className="meteo-lbl">A carregar…</span>
        </div>
      )}

      {error && (
        <div className="meteo-verdict" style={{ background: 'var(--ov-cloud)', color: 'var(--ov-slate)' }}>
          Dados meteorológicos indisponíveis
        </div>
      )}

      {weather && !error && (
        <>
          <div className="meteo-row">
            <span className="meteo-lbl">Temperatura</span>
            <span className="meteo-val">{weather.temperature}°C</span>
          </div>
          <div className="meteo-row">
            <span className="meteo-lbl">Vento</span>
            <span className="meteo-val">{Math.round(weather.windspeed)} km/h {windDir(weather.winddirection)}</span>
          </div>
          <div className="meteo-row">
            <span className="meteo-lbl">Condições</span>
            <span className="meteo-val">{wmoCodeToLabel(weather.weathercode)}</span>
          </div>
          <div className="meteo-row">
            <span className="meteo-lbl">Pôr do sol</span>
            <span className="meteo-val">{sunsetPortugal()}</span>
          </div>
          <div
            className="meteo-verdict"
            style={good ? undefined : { background: 'var(--ov-banned-bg)', color: 'var(--ov-banned-fg)' }}
          >
            {good ? 'Boas condições para voar' : `Vento ${Math.round(weather.windspeed)} km/h — não recomendado`}
          </div>
        </>
      )}
    </>
  )
}
