import { useState, useEffect } from 'react';
import { supabase } from '@/db/supabase';

interface WeatherForecast {
  date: string;
  temp_min: number;
  temp_max: number;
  temp_day: number;
  feels_like_day: number;
  humidity: number;
  wind_speed: number;
  weather_main: string;
  weather_description: string;
  weather_icon: string;
  pop: number;
}

interface WeatherData {
  forecasts: WeatherForecast[];
  location: {
    lat: number;
    lon: number;
    timezone: string;
  };
  units: string;
}

export function useWeatherForecast(
  lat: number | null,
  lon: number | null,
  startDate: string | null,
  endDate: string | null,
  enabled: boolean = true
) {
  const [weatherData, setWeatherData] = useState<WeatherData | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!enabled || !lat || !lon || !startDate || !endDate) {
      return;
    }

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

        const { data, error: functionError } = await supabase.functions.invoke('get-weather-forecast', {
          body: {
            lat,
            lon,
            start_date: startDate,
            end_date: endDate,
            units: 'metric',
            lang: 'tr',
          },
        });

        if (functionError) {
          console.error('Hava durumu hatası:', functionError);
          const errorMsg = await functionError?.context?.text?.();
          if (errorMsg) {
            try {
              const errorData = JSON.parse(errorMsg);
              setError(errorData.message || errorData.error || 'Hava durumu verisi alınamadı');
            } catch {
              setError('Hava durumu verisi alınamadı');
            }
          } else {
            setError('Hava durumu verisi alınamadı');
          }
          return;
        }

        if (data?.error) {
          console.error('Hava durumu API hatası:', data.error);
          setError(data.message || data.error);
          return;
        }

        setWeatherData(data);
      } catch (err: any) {
        console.error('Hava durumu fetch hatası:', err);
        setError('Hava durumu yüklenirken bir hata oluştu');
      } finally {
        setLoading(false);
      }
    };

    fetchWeather();
  }, [lat, lon, startDate, endDate, enabled]);

  return {
    weatherData,
    forecasts: weatherData?.forecasts || [],
    loading,
    error,
    refetch: () => {
      if (lat && lon && startDate && endDate) {
        setWeatherData(null);
        setError(null);
      }
    },
  };
}
