import React, { useEffect, useRef, useState } from "react";
import AvatarDefault from "../../assets/images/avatar_default.png";
import Banner from "../../components/Banner/banner";
import Footer from "../../components/Footer";
import { useAccountStore } from "../../store/accountStore";
import { useAppStore } from "../../store/appStore";
import { useCategoryStore } from "../../store/categoryStore";
import { useNewsStore } from "../../store/newsStore";
import { useProductStore } from "../../store/productStore";
import { alerts } from "../../utils/alerts";
import ProductItem from "../Product/ProductItem";
import SkeletonProduct from "../Product/SkeletonProducts";
import { Carousel } from "../../components/Carousel/Carousel";
import { Link } from "react-router-dom";
import {
  IconAccumulatePoints,
  IconBell,
  IconComment,
  IconDiscount,
  IconDiscountBanner,
  IconFilter,
  IconLocation,
  IconMessageBanner,
  IconNew,
  IconOrder,
  IconQr,
  IconSearch,
} from "../../components/Icon";
import { useNavigate } from "react-router";

const Home = () => {
  const navigate = useNavigate();
  const { appTheme } = useAppStore((state) => state);
  const { color_main_1 } = appTheme;
  const accountStore = useAccountStore((state) => state);
  const { avatar_image, name } = accountStore.accountInfo;
  const profile = JSON.parse(localStorage.getItem("profile"));

  const productStore = useProductStore((state) => state);
  const newsStore = useNewsStore((state) => state);
  const categoryStore = useCategoryStore((state) => state);

  const { getAllProduct, productsList } = productStore;
  const { allCategory, categories } = categoryStore;
  const { getAllPost, news } = newsStore;

  const [scrollY, setScrollY] = useState(0);
  const myRef = useRef();

  useEffect(() => {
    getAllProduct(
      (response) => {},
      (error) => {
        console.log("error: ", error);
      }
    );
    allCategory(
      (response) => {},
      (error) => {
        alerts.error(error.response.data.msg);
      }
    );
    getAllPost(
      (response) => {
        console.log("response: ", response);
      },
      (error) => {
        alerts.error(error.response.data.msg);
      }
    );
  }, []);

  const handleScroll = () => {
    if (myRef) {
      const scrollTop = myRef.current.scrollTop;
      setScrollY(scrollTop);
    }
  };

  const headerStyle = {
    top: scrollY > 50 ? "-64px" : "0",
    transition: "all 0.5s linear",
  };

  const styleRef = {
    height: scrollY > 50 ? "calc(100vh - 50px)" : "calc(100vh - 85px)",
  };

  const myUtilities = [
    // {
    //   icon: <IconQr className="text-[#65B195]" />,
    //   bgColor: "#65B1951A",
    //   name: "Quét mã QR",
    // },
    {
      icon: <IconNew className="text-[#FE8366]" />,
      bgColor: "#FE83661A",
      name: "Sản phẩm mới",
      path: "/products",
    },
    {
      icon: <IconAccumulatePoints className="text-[#FECF56]" />,
      bgColor: "#FECF561A",
      name: "Tích điểm",
      path: "/coins",
    },
    // {
    //   icon: <IconMessageBanner className="text-[#A38DE8]" />,
    //   bgColor: "#A38DE81A",
    //   name: "Nhắn tin cho shop",
    // },
    {
      icon: <IconLocation className="text-[#127ED9]" />,
      bgColor: "#127ED90D",
      name: "Địa chỉ",
      path: "/my-address",
    },
    {
      icon: <IconDiscountBanner className="text-[#65B195] w-[24px] h-[24px]" />,
      bgColor: "#65B1951A",
      name: "Voucher",
      path: "/voucher-wallet",
    },
    {
      icon: <IconOrder className="text-[#A38DE8]" />,
      bgColor: "#A38DE81A",
      name: "Đơn hàng",
      path: "/orders",
    },
  ];

  const SkeletonCategory = () => {
    return (
      <div className="flex gap-[8px] overflow-y-hidden pl-[12px] mr-[16px] animate-pulse">
        <p className="w-[70px] h-[32px] bg-gray-200 px-[10px] py-[6px] rounded-[8px]"></p>
        <p className="w-[70px] h-[32px] bg-gray-200 px-[10px] py-[6px] rounded-[8px]"></p>
        <p className="w-[70px] h-[32px] bg-gray-200 px-[10px] py-[6px] rounded-[8px]"></p>
      </div>
    );
  };

  const renderCategory = () => {
    if (categoryStore.loading && !categories.length)
      return <SkeletonCategory />;
    return (
      <div className="flex gap-[8px] overflow-y-hidden pl-[12px] mr-[16px] hidden-scrollbar">
        {categories && categories.length
          ? categories.map((item) => {
              const { id, name } = item;
              return (
                <p
                  key={id}
                  className="first:bg-primary first:text-white text-[12px] text-center bg-[#127ED90D] text-primary whitespace-nowrap px-[10px] py-[6px] rounded-[8px]"
                  onClick={() => navigate("/products")}
                >
                  {name}
                </p>
              );
            })
          : null}
      </div>
    );
  };

  const renderProductList = () => {
    if (!productsList && !productsList.length)
      return <div>Không có sản phẩm nào</div>;
    if (productStore.loading && !productsList.length)
      return (
        <div className="mt-[20px] grid grid-cols-2 sm:grid-cols-3 gap-4 pl-[12px] mr-[16px] mb-[20px]">
          <SkeletonProduct />
        </div>
      );
    return (
      <div className="mt-[20px] grid grid-cols-2 sm:grid-cols-3 gap-4 pl-[12px] mr-[16px] mb-[20px]">
        {productsList && productsList.length
          ? productsList.map((item, index) => {
              if (index > 5) return null;
              return <ProductItem product={item} key={item.id} />;
            })
          : null}
      </div>
    );
  };

  const renderNewList = () => {
    return (
      <div
        id="news"
        className="hidden-scrollbar mb-10 overflow-x-scroll flex gap-[12px] pl-[16px] mr-[16px]"
      >
        {news && news.length
          ? news.map((slide) => {
              const { id, title, image_url, summary } = slide;
              return (
                <div id={id} className="w-[250px]" key={id}>
                  <Link to={`/news/${slide.id}`}>
                    <div className="w-[250px] h-[150px]">
                      <img
                        className="w-full h-full object-cover rounded-[8px]"
                        src={image_url}
                        alt="posts"
                      />
                    </div>
                    <div className="text-[12px] mt-[10px]">
                      <p className="text-[#09101D] font-semibold line-camp-two">
                        {title}
                      </p>
                      <p className="text-[#64748B] line-camp-three mt-[6px]">
                        {summary}
                      </p>
                    </div>
                  </Link>
                </div>
              );
            })
          : null}
      </div>
    );
  };

  return (
    <div
      className=" bg-[#fcfcff] h-[calc(100vh-200px)] overflow-y-scroll"
      onScroll={handleScroll}
      ref={myRef}
      style={styleRef}
    >
      <div>
        <div
          style={headerStyle}
          id="myHeader"
          className="fixed top-0 bg-white h-[135px] w-[100vw] z-[100] shadow-[0px_0px_16px_10px_rgba(0,0,0,0.1)]"
        >
          <header className="flex items-center justify-between mt-[20px] px-[16px]">
            <div className="flex gap-[8px] items-center text-[16px]">
              <img
                className="w-[40px] h-[40px] object-cover rounded-full"
                src={profile ? avatar_image || AvatarDefault : AvatarDefault}
              />
              <p className="font-semibold text-[14px]">
                Xin chào
                <span className="text-primary" style={{ color: color_main_1 }}>
                  {name ? `, ${name}` : ""}
                </span>
              </p>
            </div>
            {/* <div className="flex items-center gap-[12px]">
              <IconBell className="text-black" />
              <IconComment className="text-black w-[18px] h-[18px]" />
            </div> */}
          </header>
          <div className=" mt-[18px] mb-[4px] px-[16px] relative">
            <input
              onClick={() => navigate("/products")}
              type="text"
              placeholder="Tìm kiếm trong cửa hàng..."
              className="w-full bg-[#FAFAFB] text-[14px] p-[12px] rounded-[8px] pl-[50px] outline-primary"
            />
            <div className="absolute top-[50%] translate-y-[-50%] left-[30px]">
              <IconSearch className="text-[#747B84]" />
            </div>
          </div>
        </div>
        <div className="h-[135px] bg-transparent"></div>
        <div id="banner" className="mt-[20px] px-[16px]">
          <Banner></Banner>
        </div>

        <div className="mt-[10px] pt-[10px]">
          <div className="flex justify-between mb-[12px] px-[16px] mt-[10px]">
            <p className="font-semibold">Tiện ích của tôi</p>
            {/* <p
              className="font-semibold text-primary text-[12px]"
              style={{ color: color_main_1 }}
            >
              Tất cả
            </p> */}
          </div>
          <div className="hidden-scrollbar flex gap-[22px] overflow-x-scroll pl-[12px] mr-[12px] overflow-y-hidden">
            {myUtilities.length
              ? myUtilities.map((item) => {
                  const { icon, bgColor, name, path } = item;
                  return (
                    <div
                      className="w-[56px]"
                      key={name}
                      onClick={() => navigate(path)}
                    >
                      <div
                        className={`p-[16px] rounded-full`}
                        style={{ backgroundColor: `${bgColor}` }}
                      >
                        {icon}
                      </div>
                      <div className="text-[10px] text-center w-[60px] mt-[8px] leading-[12px]">
                        {name}
                      </div>
                    </div>
                  );
                })
              : null}
          </div>
        </div>

        <div className="mt-[26px]">
          <div className="flex justify-between mb-[12px] px-[16px]">
            <p className="font-semibold">Danh mục sản phẩm</p>
            <p
              className="font-semibold text-primary"
              style={{ color: color_main_1 }}
            >
              <IconFilter
                className={`text-${color_main_1}`}
                onClick={() => navigate("/products")}
              />
            </p>
          </div>
          {renderCategory()}
        </div>

        {renderProductList()}

        <div className="">
          <div className="flex justify-between mb-[12px] px-[16px] mt-[10px]">
            <p className="font-semibold">Tin tức</p>
            <Link to="/news">
              <p
                className="font-semibold text-primary text-[12px]"
                style={{ color: color_main_1 }}
              >
                Tất cả
              </p>
            </Link>
          </div>
          {renderNewList()}
        </div>
      </div>
      <Footer></Footer>
    </div>
  );
};
export default Home;
