import React, { useState, useEffect } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Calendar as CalendarComponent } from '@/components/ui/calendaredit';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
  Sun,
  Cloud,
  CloudRain,
  CloudDrizzle,
  CloudSnow,
  CloudLightning,
  CloudFog,
  CloudSun,
  CircleAlert,
  Tornado,
  Haze,
  Moon,
  Wind,
  Droplets,
  ThermometerSun,
  ThermometerSnowflake,
  Sunrise,
  Sunset,
  AlertTriangle,
  Umbrella,
  ChevronLeft,
  ChevronRight
} from 'lucide-react';
import { cn } from "@/lib/utils";

const DateTimeWeatherDisplay = ({ scaleFactor = 1 }) => {
  const [datetime, setDatetime] = useState(new Date());
  const [prevTime, setPrevTime] = useState(getTimeComponents(new Date()));
  const [isTimeChanging, setIsTimeChanging] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [weather, setWeather] = useState(null);
  const [forecast, setForecast] = useState(null);

  useEffect(() => {
    setTimeout(() => setMounted(true), 150);

    const timer = setInterval(() => {
      const newDate = new Date();
      const newTime = getTimeComponents(newDate);
      
      if (newTime.minutes !== prevTime.minutes) {
        setIsTimeChanging(true);
        setTimeout(() => setIsTimeChanging(false), 200);
      }
      
      setPrevTime(newTime);
      setDatetime(newDate);
    }, 1000);
    return () => clearInterval(timer);
  }, [prevTime]);

  useEffect(() => {
    const fetchWeatherData = async () => {
      try {
        const API_KEY = import.meta.env.VITE_OPENWEATHER_API_KEY;
        const [weatherResponse, forecastResponse] = await Promise.all([
          fetch(
            `https://api.openweathermap.org/data/2.5/weather?lat=43.63507&lon=-84.18995&appid=${API_KEY}&units=imperial`
          ),
          fetch(
            `https://api.openweathermap.org/data/2.5/forecast?lat=43.63507&lon=-84.18995&appid=${API_KEY}&units=imperial`
          )
        ]);
        
        const weatherData = await weatherResponse.json();
        const forecastData = await forecastResponse.json();
        
        setWeather(weatherData);
        
        // Process forecast data to get daily forecasts with precipitation
        const dailyForecasts = forecastData.list.reduce((acc, item) => {
          const date = new Date(item.dt * 1000).toLocaleDateString();
          if (!acc[date]) {
            acc[date] = {
              ...item,
              precipitation: item.rain?.['3h'] || item.snow?.['3h'] || 0,
              pop: item.pop * 100 // Probability of precipitation as percentage
            };
          }
          return acc;
        }, {});
        
        setForecast(Object.values(dailyForecasts).slice(0, 5));
      } catch (error) {
        console.error("Error fetching weather:", error);
      }
    };

    fetchWeatherData();
    const weatherTimer = setInterval(fetchWeatherData, 300000);
    return () => clearInterval(weatherTimer);
  }, []);

  function getTimeComponents(date) {
    let hours = date.getHours();
    const minutes = date.getMinutes();
    const ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12;
    return {
      hours: hours.toString(),
      minutes: minutes.toString().padStart(2, '0'),
      ampm
    };
  }

  const formatDate = (date) => {
    return {
      weekday: date.toLocaleDateString('en-US', { weekday: 'long' }),
      month: date.toLocaleDateString('en-US', { month: 'long' }),
      day: date.getDate()
    };
  };

  const getWeatherIcon = (weatherCode, currentTime, small = false) => {
    if (!weatherCode) return <CircleAlert className="w-12 h-12 text-red-500" />;
    const code = parseInt(weatherCode, 10);
    const iconProps = small ? "w-8 h-8" : "w-12 h-12";
    switch (true) {
      case code >= 200 && code < 300:
        return <CloudLightning className={cn(iconProps, "text-gray-700")} />;
      case code >= 300 && code < 500:
        return <CloudDrizzle className={cn(iconProps, "text-blue-600")} />;
      case code >= 500 && code < 600:
        return <CloudRain className={cn(iconProps, "text-blue-600")} />;
      case code >= 600 && code < 700:
        return <CloudSnow className={cn(iconProps, "text-blue-400")} />;
      case code >= 700 && code < 721:
        return <CloudFog className={cn(iconProps, "text-gray-600")} />;
      case code === 721:
        return <Haze className={cn(iconProps, "text-gray-700")} />;
      case code >= 722 && code < 781:
        return <CloudFog className={cn(iconProps, "text-gray-600")} />;
      case code === 781:
        return <Tornado className={cn(iconProps, "text-gray-700")} />;
      case code === 800:
        return currentTime.getHours() >= 6 && currentTime.getHours() < 18 ? (
          <Sun className={cn(iconProps, "text-yellow-700")} />
        ) : (
          <Moon className={cn(iconProps, "text-gray-500")} />
        );
      case code >= 800 && code < 803:
        return <CloudSun className={cn(iconProps, "text-gray-600")} />;
      case code >= 803:
        return <Cloud className={cn(iconProps, "text-gray-600")} />;
      default:
        return <CircleAlert className={cn(iconProps, "text-red-700")} />;
    }
  };

  const getWeatherBackground = (weatherCode, isNight) => {
    const code = parseInt(weatherCode, 10);
    
    // Thunderstorm (200-299)
    if (code >= 200 && code < 300) {
      return "bg-gradient-to-br from-slate-900 via-purple-900 to-slate-800";
    }
    
    // Drizzle (300-399)
    if (code >= 300 && code < 400) {
      return "bg-gradient-to-br from-slate-700 via-blue-800 to-slate-700";
    }
    
    // Rain (500-599)
    if (code >= 500 && code < 600) {
      return "bg-gradient-to-br from-slate-800 via-blue-900 to-slate-700";
    }
    
    // Snow (600-699)
    if (code >= 600 && code < 700) {
      return "bg-gradient-to-br from-slate-200 via-blue-100 to-slate-100";
    }
    
    // Atmosphere (700-799: mist, smoke, haze, fog, etc.)
    if (code >= 700 && code < 800) {
      return "bg-gradient-to-br from-slate-600 via-slate-500 to-slate-400";
    }
    
    // Clear (800)
    if (code === 800) {
      if (isNight) {
        return "bg-gradient-to-br from-slate-900 via-blue-950 to-slate-800";
      }
      return "bg-gradient-to-br from-sky-400 via-blue-400 to-sky-500";
    }
    
    // Clouds (801-804)
    if (code > 800) {
      if (isNight) {
        return "bg-gradient-to-br from-slate-800 via-slate-700 to-slate-600";
      }
      return "bg-gradient-to-br from-slate-400 via-slate-500 to-slate-400";
    }
    
    // Default fallback
    return "bg-gradient-to-br from-slate-700 via-slate-600 to-slate-500";
  };
  
  const getTemperatureColor = (weatherCode, isNight) => {
    const code = parseInt(weatherCode, 10);
    
    // Use dark text for light backgrounds
    if (code >= 600 && code < 700) { // Snow
      return "text-slate-900";
    }
    
    if (code === 800 && !isNight) { // Clear day
      return "text-slate-900";
    }
    
    if (code > 800 && !isNight) { // Cloudy day
      return "text-slate-900";
    }
    
    // Default to white text for all other (darker) backgrounds
    return "text-white";
  };

  const { hours, minutes, ampm } = getTimeComponents(datetime);
  const dateInfo = formatDate(datetime);

  const formatTime = (timestamp) => {
    if (!timestamp) return '--:--';
    const date = new Date(timestamp * 1000);
    return date.toLocaleTimeString('en-US', { 
      hour: 'numeric',
      minute: '2-digit',
      hour12: true 
    });
  };

  const WeatherDetails = () => (
    <div className="space-y-4 p-3">
   <div className="grid grid-cols-3 gap-2">
      <Card className="p-2">
        <div className="flex items-center gap-1">
          <ThermometerSun className="w-5 h-5 text-orange-500" />
          <div className="flex flex-col">
            <span className="text-xs text-muted-foreground">High</span>
            <span className="text-sm font-bold">{Math.round(weather.main.temp_max)}°F</span>
          </div>
        </div>
      </Card>
      
      <Card className="p-2">
        <div className="flex items-center gap-1">
          <ThermometerSnowflake className="w-5 h-5 text-blue-500" />
          <div className="flex flex-col">
            <span className="text-xs text-muted-foreground">Low</span>
            <span className="text-sm font-bold">{Math.round(weather.main.temp_min)}°F</span>
          </div>
        </div>
      </Card>

      <Card className="p-2">
        <div className="flex items-center gap-1">
          <Droplets className="w-5 h-5 text-blue-400" />
          <div className="flex flex-col">
            <span className="text-xs text-muted-foreground">Humidity</span>
            <span className="text-sm font-bold">{weather.main.humidity}%</span>
          </div>
        </div>
      </Card>

      <Card className="p-2">
        <div className="flex items-center gap-1">
          <Wind className="w-5 h-5 text-gray-500" />
          <div className="flex flex-col">
            <span className="text-xs text-muted-foreground">Wind</span>
            <span className="text-sm font-bold">{Math.round(weather.wind.speed)} mph</span>
          </div>
        </div>
      </Card>

      <Card className="p-2">
        <div className="flex items-center gap-1">
          <Sunrise className="w-5 h-5 text-yellow-500" />
          <div className="flex flex-col">
            <span className="text-xs text-muted-foreground">Sunrise</span>
            <span className="text-sm font-bold">{formatTime(weather.sys?.sunrise)}</span>
          </div>
        </div>
      </Card>

      <Card className="p-2">
        <div className="flex items-center gap-1">
          <Sunset className="w-5 h-5 text-orange-400" />
          <div className="flex flex-col">
            <span className="text-xs text-muted-foreground">Sunset</span>
            <span className="text-sm font-bold">{formatTime(weather.sys?.sunset)}</span>
          </div>
        </div>
      </Card>
    </div>

    {forecast && (
      <div>
        <div className="grid grid-cols-5 gap-2">
          {forecast.map((day, index) => (
            <Card key={index} className="p-2">
              <div className="flex flex-col items-center gap-1">
                <span className="text-sm font-medium">
                  {new Date(day.dt * 1000).toLocaleDateString('en-US', { weekday: 'short' })}
                </span>
                {getWeatherIcon(day.weather[0].id, new Date(day.dt * 1000), true)}
                <div className="flex justify-center gap-1 items-baseline w-full">
                  <span className="text-sm font-medium">
                    {Math.round(day.main.temp_max)}°
                  </span>
                  <span className="text-xs text-muted-foreground">
                    {Math.round(day.main.temp_min)}°
                  </span>
                </div>
                <div className="flex flex-col items-center gap-1 w-full pt-1">
                  {day.rain?.['3h'] > 0 && (
                    <div className="flex items-center gap-1">
                      <CloudRain className="w-3 h-3 text-blue-400" />
                      <span className="text-xs">{day.rain['3h'].toFixed(2)}"</span>
                    </div>
                  )}
                  {day.snow?.['3h'] > 0 && (
                    <div className="flex items-center gap-1">
                      <CloudSnow className="w-3 h-3 text-blue-400" />
                      <span className="text-xs">{day.snow['3h'].toFixed(2)}"</span>
                    </div>
                  )}
                  {!day.rain?.['3h'] && !day.snow?.['3h'] && (
                    <div className="flex items-center gap-1">
                      <Umbrella className="w-3 h-3 text-gray-400" />
                      <span className="text-xs">0"</span>
                    </div>
                  )}
                </div>
              </div>
            </Card>
          ))}
        </div>
      </div>
    )}
  </div>
);

return (
  <div className={`flex flex-col space-y-2 items-center w-[250px] transition-opacity duration-300 ${mounted ? 'opacity-100' : 'opacity-0'}`}>
  {/* Time Display */}
    <Card className="bg-gradient-to-br from-slate-900 via-sky-800 to-cyan-800 dark:bg-slate-800 px-1 py-2 w-full hover:scale-[1.02] transition-transform duration-300">
      <CardContent className="p-3">
        <div className="flex justify-center items-baseline">
          <div className={`transition-opacity duration-200 ${isTimeChanging ? 'opacity-60' : 'opacity-100'}`}>
            <span className="text-6xl font-bold text-white">{hours}</span>
            <span className="text-6xl font-bold text-white">:</span>
            <span className="text-6xl font-bold text-white">{minutes}</span>
            <span className="text-lg font-medium text-white/90 ml-1">{ampm}</span>
          </div>
        </div>
      </CardContent>
    </Card>

    {/* Date and Weather Display */}
    <div className="grid grid-cols-2 gap-2 w-full">
      <Card className="bg-gradient-to-br from-slate-900 via-violet-800 to-purple-800 aspect-square flex items-center justify-center">
        <CardContent className="h-full p-0">
          <div className="flex flex-col items-center justify-center h-full">
            <span className="text-6xl font-bold text-white">
              {dateInfo.day}
            </span>
            <span className="text-xs font-bold text-white/70 mt-2">
              {dateInfo.weekday}
            </span>
          </div>
        </CardContent>
      </Card>

      {weather?.main && (
  <Popover>
    <PopoverTrigger asChild>
      <Card className={cn(
        getWeatherBackground(
          weather.weather[0]?.id,
          datetime.getHours() >= 18 || datetime.getHours() < 6
        ),
        "flex items-center justify-center aspect-square cursor-pointer hover:brightness-110 transition-all relative"
      )}>
              <CardContent className="p-3">
                <div className="flex flex-col items-center">
                  {getWeatherIcon(weather.weather[0]?.id, datetime)}
                  <span className={cn(
                    "text-2xl font-bold ml-1 mt-2",
                    getTemperatureColor(
                      weather.weather[0]?.id,
                      datetime.getHours() >= 18 || datetime.getHours() < 6
                    )
                  )}>
                    {Math.round(weather.main.temp)}°
                  </span>
                </div>
              </CardContent>
              {weather.alerts && (
                <div className="absolute top-1 right-1">
                  <AlertTriangle className="w-5 h-5 text-red-500" />
                </div>
              )}
             </Card>
    </PopoverTrigger>
    <PopoverContent 
      className="w-[450px]" 
      align="start"
      side="right"
      sideOffset={10}
      style={{ 
        transform: `scale(${scaleFactor})`,
        transformOrigin: 'left top'
      }}
    >
      {weather.alerts && (
        <Alert variant="warning" className="mb-3">
          <AlertTriangle className="h-3 w-3" />
          <AlertDescription className="text-xs">
            {weather.alerts[0].event}
          </AlertDescription>
        </Alert>
      )}
      <WeatherDetails />
    </PopoverContent>
  </Popover>
)}
    </div>

    {/* Calendar Display */}
    <Card className="w-full">
      <CardContent className="p-0">
        <CalendarComponent
          selected={datetime}
          className="w-full"
        />
      </CardContent>
    </Card>
  </div>
  );
};

export default DateTimeWeatherDisplay;