import React, { useState, useEffect } from "react";
import { Card, CardContent } from "@/components/ui/card";
import {
  Calendar,
  Clock,
  Sun,
  Cloud,
  CloudRain,
  CloudDrizzle,
  CloudSnow,
  CloudLightning,
  CloudFog,
  CloudSun,
  CircleAlert,
  Tornado,
  Haze,
  Moon,
  Monitor,
} from "lucide-react";
import { useScroll } from "@/contexts/ScrollContext";
import { useTheme } from "@/components/theme/ThemeProvider";
import { cn } from "@/lib/utils";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

const CraftsIcon = () => (
  <svg viewBox="0 0 2687 3338" className="w-6 h-6" aria-hidden="true">
    <path
      fill="white"
      d="M911.230469 1807.75C974.730469 1695.5 849.919922 1700.659912 783.610352 1791.25C645.830078 1979.439941 874.950195 2120.310059 1112.429688 2058.800049C1201.44043 2035.72998 1278.759766 2003.080078 1344.580078 1964.159912C1385.389648 1940.040039 1380.900391 1926.060059 1344.580078 1935.139893C1294.040039 1947.800049 1261.69043 1953.73999 1177.700195 1966.97998C1084.719727 1981.669922 832.790039 1984.22998 911.230469 1807.75M1046.799805 1631.389893C1135.280273 1670.419922 1139.650391 1624.129883 1056.980469 1562.070068C925.150391 1463.110107 787.360352 1446.379883 661.950195 1478.280029C265.379883 1579.179932 67.740234 2077.050049 144.099609 2448.399902C357.860352 3487.689941 1934.570313 3457.959961 2143.030273 2467.540039C2204.700195 2174.439941 2141.950195 1852.780029 1917.990234 1665.149902C1773.219727 1543.870117 1575.009766 1536.659912 1403.599609 1591.72998C1380.639648 1599.110107 1381.410156 1616.610107 1403.599609 1612.379883C1571.25 1596.040039 1750.790039 1606 1856.75 1745.280029C2038.769531 1984.459961 2052.570313 2274.080078 1974.629883 2511.209961C1739.610352 3226.25 640.719727 3226.540039 401.719727 2479.26001C308.040039 2186.350098 400.299805 1788.800049 690 1639.100098C785.830078 1589.590088 907.040039 1569.709961 1046.799805 1631.389893Z"
    />
    <path
      fill="white"
      d="M1270.089844 1727.72998C1292.240234 1431.47998 1284.94043 952.430176 1257.849609 717.390137C1235.679688 525.310059 1166.200195 416.189941 1093.629883 349.390137C1157.620117 313.180176 1354.129883 485.680176 1447.830078 603.350098C1790.870117 1034.100098 2235.580078 915.060059 2523.480469 721.129883C2569.120117 680.51001 2592.900391 654.030029 2523.480469 651.339844C2260.400391 615.330078 2115 463.060059 1947.530273 293.890137C1672.870117 16.459961 1143.719727 162.169922 1033.969727 303.040039C999.339844 280.299805 966.849609 265 941.709961 252.419922C787.139648 175.160156 670.049805 223.580078 871.780273 341.569824C962.599609 394.689941 1089.849609 483.48999 1168.230469 799.589844C1222.370117 1018.040039 1230.009766 1423.919922 1242.360352 1728.379883C1247 1761.850098 1264.799805 1759.629883 1270.089844 1727.72998"
    />
  </svg>
);

const Header = () => {
  const [currentTime, setCurrentTime] = useState(new Date());
  const [weather, setWeather] = useState(null);
  const { isStuck } = useScroll();
  const { theme, systemTheme, toggleTheme, setTheme } = useTheme();

  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  useEffect(() => {
    const fetchWeather = async () => {
      try {
        const API_KEY = import.meta.env.VITE_OPENWEATHER_API_KEY;
        const response = await fetch(
          `https://api.openweathermap.org/data/2.5/weather?lat=43.63507&lon=-84.18995&appid=${API_KEY}&units=imperial`
        );
        const data = await response.json();
        setWeather(data);
      } catch (error) {
        console.error("Error fetching weather:", error);
      }
    };

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

  const getWeatherIcon = (weatherCode, currentTime) => {
    if (!weatherCode) return <CircleAlert className="w-6 h-6 text-red-500" />;

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

  const formatTime = (date) => {
    const hours = date.getHours();
    const minutes = String(date.getMinutes()).padStart(2, "0");
    const seconds = String(date.getSeconds()).padStart(2, "0");
    const period = hours >= 12 ? "PM" : "AM";
    const displayHours = hours % 12 || 12;
    return `${displayHours}:${minutes}:${seconds} ${period}`;
  };

  const formatDate = (date) =>
    date.toLocaleDateString("en-US", {
      weekday: "short",
      year: "numeric",
      month: "short",
      day: "numeric",
    });

  return (
    <Card
      className={cn(
        "w-full bg-white dark:bg-gray-900 shadow-sm",
        isStuck ? "rounded-b-lg border-b-1" : "border-b-0 rounded-b-none"
      )}
    >
      <CardContent className="p-4">
        <div className="flex flex-col justify-between lg:flex-row items-center sm:items-center flex-wrap">
          <div className="flex items-center space-x-4">
            <div className="flex space-x-2">
              <div
                onClick={toggleTheme}
                className={cn(
                  "bg-gradient-to-r from-blue-500 to-blue-600 p-3 rounded-lg shadow-md cursor-pointer hover:opacity-90 transition-opacity",
                  theme === "light" && "ring-1 ring-yellow-300",
                  theme === "dark" && "ring-1 ring-purple-300",
                  "ring-offset-2 ring-offset-white dark:ring-offset-gray-900"
                )}
              >
                <CraftsIcon />
              </div>{" "}
            </div>
            <div>
              <h1 className="text-2xl font-bold bg-gradient-to-r from-blue-600 to-blue-400 bg-clip-text text-transparent">
                Store Status
              </h1>
            </div>
          </div>
          <div className="flex items-left sm:items-center justify-center flex-wrap mt-2 sm:mt-0">
            {weather?.main && (
              <>
                <div className="flex-col items-center text-center">
                  <div className="items-center justify-center space-x-2 rounded-lg px-4 hidden sm:flex">
                    {getWeatherIcon(weather.weather[0]?.id, currentTime)}
                    <div>
                      <p className="text-xl font-bold tracking-tight dark:text-gray-100">
                        {Math.round(weather.main.temp)}° F
                      </p>
                    </div>
                  </div>
                </div>
              </>
            )}
            <div className="h-10 w-px bg-gradient-to-b from-gray-200 to-gray-200 dark:from-gray-700 dark:to-gray-700 hidden sm:block"></div>
            <div className="flex items-center space-x-1 sm:space-x-3 rounded-lg px-4 py-2">
              <Calendar className="w-5 h-5 text-green-500 shrink-0" />
              <div>
                <p className="text-sm sm:text-xl font-bold tracking-tight p-0 dark:text-gray-100">
                  {formatDate(currentTime)}
                </p>
              </div>
            </div>
            <div className="h-10 w-px bg-gradient-to-b from-gray-200 to-gray-200 dark:from-gray-700 dark:to-gray-700 hidden sm:block"></div>
            <div className="flex items-center space-x-1 sm:space-x-3 rounded-lg px-4 py-2">
              <Clock className="w-5 h-5 text-blue-500 shrink-0" />
              <div>
                <p className="text-md sm:text-xl font-bold tracking-tight tabular-nums dark:text-gray-100 mr-2">
                  {formatTime(currentTime)}
                </p>
              </div>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
};

export default Header;
