"use client";

import { useEffect, useState } from "react";
import { Cloud, Sun, CloudRain, Wind, Droplets, Loader2, Clock } from "lucide-react";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";

interface WeatherData {
  temperature: number;
  condition: string;
  windSpeed: number;
  humidity: number;
  weatherCode: number;
}

// Coordonnées de Fakarava (Rotoava)
const FAKARAVA_LAT = -16.3167;
const FAKARAVA_LON = -145.6167;

// Codes météo Open-Meteo vers descriptions
const getWeatherCondition = (code: number): { text: string; icon: React.ReactNode } => {
  // Codes Open-Meteo WMO Weather interpretation codes
  if (code === 0) {
    return { text: "Ciel dégagé", icon: <Sun className="h-16 w-16 text-yellow-400" /> };
  } else if (code <= 3) {
    return { text: "Partiellement nuageux", icon: <Cloud className="h-16 w-16 text-gray-400" /> };
  } else if (code <= 48) {
    return { text: "Nuageux", icon: <Cloud className="h-16 w-16 text-gray-500" /> };
  } else if (code <= 55) {
    return { text: "Brouillard", icon: <Cloud className="h-16 w-16 text-gray-400" /> };
  } else if (code <= 67) {
    return { text: "Pluie", icon: <CloudRain className="h-16 w-16 text-blue-400" /> };
  } else if (code <= 77) {
    return { text: "Neige", icon: <CloudRain className="h-16 w-16 text-gray-300" /> };
  } else if (code <= 82) {
    return { text: "Averses", icon: <CloudRain className="h-16 w-16 text-blue-500" /> };
  } else if (code <= 86) {
    return { text: "Averses de neige", icon: <CloudRain className="h-16 w-16 text-gray-300" /> };
  } else {
    return { text: "Orage", icon: <CloudRain className="h-16 w-16 text-purple-500" /> };
  }
};

export default function WeatherWidget() {
  const [weather, setWeather] = useState<WeatherData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [localTime, setLocalTime] = useState<string>("");

  // Mise à jour de l'heure locale chaque seconde
  useEffect(() => {
    const updateTime = () => {
      const now = new Date();
      // Fuseau horaire de Tahiti (UTC-10)
      const tahitiTime = new Date(now.toLocaleString("en-US", { timeZone: "Pacific/Tahiti" }));
      const hours = tahitiTime.getHours().toString().padStart(2, "0");
      const minutes = tahitiTime.getMinutes().toString().padStart(2, "0");
      setLocalTime(`${hours}:${minutes}`);
    };

    updateTime();
    const timeInterval = setInterval(updateTime, 1000);
    return () => clearInterval(timeInterval);
  }, []);

  useEffect(() => {
    const fetchWeather = async () => {
      try {
        setLoading(true);
        setError(null);

        // API Open-Meteo (gratuit, pas de clé API nécessaire)
        const response = await fetch(
          `https://api.open-meteo.com/v1/forecast?latitude=${FAKARAVA_LAT}&longitude=${FAKARAVA_LON}&current=temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m&wind_speed_unit=kmh&timezone=Pacific/Tahiti`
        );

        if (!response.ok) {
          throw new Error("Erreur lors de la récupération de la météo");
        }

        const data = await response.json();
        const current = data.current;

        setWeather({
          temperature: Math.round(current.temperature_2m),
          condition: getWeatherCondition(current.weather_code).text,
          windSpeed: Math.round(current.wind_speed_10m),
          humidity: current.relative_humidity_2m,
          weatherCode: current.weather_code,
        });
      } catch (err) {
        console.error("Erreur météo:", err);
        setError("Impossible de charger la météo");
        // Valeurs par défaut en cas d'erreur
        setWeather({
          temperature: 28,
          condition: "Ensoleillé",
          windSpeed: 15,
          humidity: 75,
          weatherCode: 0,
        });
      } finally {
        setLoading(false);
      }
    };

    fetchWeather();

    // Rafraîchir toutes les heures
    const interval = setInterval(fetchWeather, 3600000);
    return () => clearInterval(interval);
  }, []);

  if (loading) {
    return (
      <Card className="bg-gradient-to-br from-primary/10 to-secondary">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Sun className="h-6 w-6 text-primary" />
            Météo - Fakarava
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center py-8">
            <Loader2 className="h-8 w-8 animate-spin text-primary" />
          </div>
        </CardContent>
      </Card>
    );
  }

  if (!weather) {
    return null;
  }

  const weatherInfo = getWeatherCondition(weather.weatherCode);

  return (
    <Card className="bg-gradient-to-br from-primary/10 to-secondary">
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Sun className="h-6 w-6 text-primary" />
            Météo - Fakarava
          </div>
          {localTime && (
            <div className="flex items-center gap-1 text-sm font-normal text-gray-600 dark:text-gray-400">
              <Clock className="h-4 w-4" />
              {localTime}
            </div>
          )}
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="flex items-center justify-between">
          <div>
            <p className="text-3xl font-bold text-primary">{weather.temperature}°C</p>
            <p className="text-gray-600 dark:text-gray-300 mt-1">{weather.condition}</p>
            {error && (
              <p className="text-xs text-orange-500 mt-1">Données en cache</p>
            )}
          </div>
          <div className="text-6xl">{weatherInfo.icon}</div>
        </div>
        <div className="mt-4 flex gap-4 text-sm text-gray-600 dark:text-gray-400">
          <div className="flex items-center gap-1">
            <Wind className="h-4 w-4" />
            <span className="font-semibold">Vent:</span> {weather.windSpeed} km/h
          </div>
          <div className="flex items-center gap-1">
            <Droplets className="h-4 w-4" />
            <span className="font-semibold">Humidité:</span> {weather.humidity}%
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
