"use client";
import type React from "react";
import {
  createContext,
  useContext,
  useState,
  useEffect,
  useCallback,
} from "react";
import { useDispatch } from "react-redux";
import { setIsMobileScreen } from "@/src/redux/appActions";

export const BREAKPOINTS = {
  xs: 480,
  sm: 640,
  md: 768,
  lg: 1024,
  xl: 1280,
  "2xl": 1536,
};

type ScreenSizeContextType = {
  isMobile: boolean;
  isTablet: boolean;
  isDesktop: boolean;
  currentBreakpoint: string;
  width: number;
  isClient: boolean; // track if we're on the client
};

const defaultContext: ScreenSizeContextType = {
  isMobile: false,
  isTablet: false,
  isDesktop: true,
  currentBreakpoint: "xl",
  width: 1280,
  isClient: false, // Default to false (server)
};

const ScreenSizeContext = createContext<ScreenSizeContextType>(defaultContext);

interface ScreenSizeProviderProps {
  children: React.ReactNode;
  mobileBreakpoint?: number;
  tabletBreakpoint?: number;
}

export const ScreenSizeProvider = ({
  children,
  mobileBreakpoint = 767,
  tabletBreakpoint = 1024,
}: ScreenSizeProviderProps) => {
  const dispatch = useDispatch();
  const [screenSize, setScreenSize] =
    useState<ScreenSizeContextType>(defaultContext);

  const determineBreakpoint = (width: number): string => {
    if (width < BREAKPOINTS.xs) return "xs";
    if (width < BREAKPOINTS.sm) return "sm";
    if (width < BREAKPOINTS.md) return "md";
    if (width < BREAKPOINTS.lg) return "lg";
    if (width < BREAKPOINTS.xl) return "xl";
    return "2xl";
  };

  const updateScreenSize = useCallback(() => {
    if (typeof window !== "undefined") {
      const width = window.innerWidth;

      // Clear definitions for different device types
      const isMobile = width <= mobileBreakpoint;
      const isTablet = width > mobileBreakpoint && width < tabletBreakpoint;
      const isDesktop = width >= tabletBreakpoint;
      const currentBreakpoint = determineBreakpoint(width);

      console.log(
        `Setting screen size - Width: ${width}px, Mobile: ${isMobile}, Tablet: ${isTablet}, Desktop: ${isDesktop}`
      );

      setScreenSize({
        isMobile,
        isTablet,
        isDesktop,
        currentBreakpoint,
        width,
        isClient: true, // We're on the client
      });

      // Update Redux state
      dispatch(setIsMobileScreen(isMobile));
    }
  }, [dispatch, mobileBreakpoint, tabletBreakpoint]);

  // Initial setup
  useEffect(() => {
    // Only run on client
    if (typeof window === "undefined") return;

    // Set isClient to true immediately
    setScreenSize((prev) => ({ ...prev, isClient: true }));

    updateScreenSize();

    window.addEventListener("resize", updateScreenSize);

    return () => window.removeEventListener("resize", updateScreenSize);
  }, [updateScreenSize]);

  return (
    <ScreenSizeContext.Provider value={screenSize}>
      {children}
    </ScreenSizeContext.Provider>
  );
};

export const useScreenSizeContext = (): ScreenSizeContextType => {
  const context = useContext(ScreenSizeContext);

  // Prevent useContext crash during SSR
  if (typeof window === "undefined") {
    return defaultContext;
  }

  return context;
};
