"use client";

import { useEffect, useState } from "react";
import Brands from "@/components/brands";
import ProductList from "@/components/product-list";
import Services from "@/components/services";
import Slider from "@/components/slider";
import { useTranslations, useLocale } from "next-intl";
import axios from "../../utils/axios-config";

import {
  fetchAddressSuccess,
  fetchAddressIdSuccess,
} from "@/store/address/actions";
import { fetchSlidersSuccess } from "@/store/sliders/actions";
import { fetchLanguage } from "@/store/languageSwitcher/actions";
import { fetchCartSuccess, FETCH_CART_LENGTH,fetchCartLength } from "@/store/cart/actions";
import { useDispatch, useSelector } from "react-redux";
import { fetchCategoriesSuccess } from "@/store/category/actions";
import Image from "next/image";
import Cookies from "js-cookie";
import ProductsSlider from "@/components/products-slider";

export default function Home(props: any) {
  const [categories, setCategories] = useState<any>([]);
  const [banners, setBanners] = useState<any>([]);
  const [featuredProducts, setFeaturedProducts] = useState<any>([]);
  const locale = useLocale();
  //console.log({ locale });
  const dispatch = useDispatch();
  const { brands, error, loading } = useSelector(
    (state: { Brands: any }) => state.Brands
  );
  const { idToken } = useSelector((state: { Auth: any }) => state.Auth);
  const direction = locale === "ar" ? "rtl" : "ltr";
  const t = useTranslations();
  const { searchValue } = useSelector((state: { Search: any }) => state.Search);
  const { addressId } = useSelector((state: { Address: any }) => state.Address);

  // useEffect(() => {
  // Get the saved locale from cookies, default to 'ar'
  // const savedLocale = Cookies.get("NEXT_LOCALE") || "ar";

  // Dispatch Redux action to update language state
  // dispatch(fetchLanguage(savedLocale));

  // Store the language in cookies if not already set
  // if (!Cookies.get("NEXT_LOCALE")) {
  //   Cookies.set("NEXT_LOCALE", savedLocale, { path: "/" });
  // }
  // }, [dispatch]);
  /// get addresses
   const fetchSliders = async () => {
      try {
        const response = await axios.get("/sliders");
        if (response?.data?.status) {
          const data = await response?.data?.data;
  dispatch(fetchSlidersSuccess(data));
        
        }
      } catch (error) {
        // console.error("Failed to fetch favorites:", error);
      }
    };
  
    useEffect(() => {
      fetchSliders();
    }, []);

  useEffect(() => {
    const fetchAddressesData = async () => {
      try {
        const response = await axios.get(`addresses`);

        const { data } = await response?.data;

        dispatch(fetchAddressSuccess(data));
        // if (!addressId) {
        //   dispatch(fetchAddressIdSuccess(data[0]?.id));
        // }
      } catch (err: any) {}
    };
    if (idToken) {
      fetchAddressesData();
    }
  }, []);

 
  // useEffect(() => {
  //   const fetchCartData = async () => {
  //     try {
  //       const response = await axios.get("/my-cart");
  //       const data = await response?.data?.data;
  //       // console.log("cart", data);
  //       //fetchCartLength(data?.products?.length);
  //       dispatch({ type: FETCH_CART_LENGTH, payload: data?.products?.length });
  //       dispatch(fetchCartLength(Number(data?.products?.length)))
  //       fetchCartSuccess(data?.products);

  //       // setBanners([...data]);
  //     } catch (err) {}
  //   };
  //   if (idToken) {
  //     fetchCartData();
  //   }
  // }, []);
 
  useEffect(() => {
    const fetchHomeData = async () => {
      try {
        const response = await axios.get("/home");
        //console.log('HomeData',response?.data?.data);
        const data = await response?.data?.data;
       
         dispatch(fetchCartLength(Number(response?.headers['x-cartitems-count']) || 0))
        setFeaturedProducts([...data?.featured]);
        setCategories([...data?.categories]);
        dispatch(fetchCategoriesSuccess(data?.categories));
      } 
      catch (err) {

      }
    };
    fetchHomeData();
  }, []);

  // const { locale } = await props.params; // Ensure you resolve `params` if it's a promise.
  return (
    <div className="">
      {/* <Health /> */}
      {/* <button onClick={() => { throw new Error("Test Sentry"); }}>Test</button> */}


      <ProductsSlider />
      <Services categories={categories} />
      <Slider />
      <Brands showPagination={false} pageSize={12} />
      <ProductList title={t("Picked For You")} products={featuredProducts} />
    </div>
  );
}
