"use client";
import React, { useState, useEffect, useCallback } from "react";
import Image from "next/image";
import { OpenAddToCartModalButton } from "@/components/common/AddToCartModal/OpenAddToCartModalButton";
// 商品类型定义
interface ProductItem {
  id: number;
  img: string;
  title: string;
  price: number;
  originPrice: number;
  star: number;
  reviewCount: number;
}

// ========== 模拟后端分页接口（真实场景替换为axios/fetch请求） ==========
/**
 * @param page 当前页码
 * @param pageSize 每页条数
 * @returns Promise<{ list: ProductItem[], total: number }>
 */
const mockGetProductApi = async (page: number, pageSize: number) => {
  // 模拟总数据22条，后端固定总数
  const TOTAL = 22;
  // 模拟全部源数据
  const allMockData: ProductItem[] = Array.from({ length: TOTAL }).map(
    (_, idx) => ({
      id: idx + 1,
      img: `/img/hair${(idx % 6) + 1}.jpg`,
      title: "14-36 In Water Wave Human Hair Wig",
      price: 143.35,
      originPrice: 143.35,
      star: 5,
      reviewCount: 342,
    }),
  );

  // 分页切片
  const start = (page - 1) * pageSize;
  const end = page * pageSize;
  const pageList = allMockData.slice(start, end);

  // 模拟网络延迟
  await new Promise((resolve) => setTimeout(resolve, 600));
  return {
    list: pageList,
    total: TOTAL,
  };
};

const PAGE_SIZE = 6;

export default function RecommendedProducts() {
  // 已渲染的全部商品
  const [productList, setProductList] = useState<ProductItem[]>([]);
  // 当前页码
  const [page, setPage] = useState(1);
  // 数据总条数
  const [total, setTotal] = useState(0);
  // 加载状态
  const [loading, setLoading] = useState(false);

  // 是否还有下一页：已渲染数量 < 总条数
  const hasMore = productList.length < total;

  // 请求分页数据
  const fetchPageData = useCallback(async (currentPage: number) => {
    setLoading(true);
    try {
      const res = await mockGetProductApi(currentPage, PAGE_SIZE);
      setTotal(res.total);
      // 函数式更新，稳定依赖
      setProductList((prev) =>
        currentPage === 1 ? res.list : [...prev, ...res.list],
      );
    } catch (err) {
      // 屏蔽 no-console 警告
      // eslint-disable-next-line no-console
      console.error("商品分页加载失败", err);
    } finally {
      setLoading(false);
    }
  }, []);

  // 页面初始化挂载只加载一次第一页
  useEffect(() => {
    // 封装内部异步函数，规范写法
    const initLoad = async () => {
      await fetchPageData(1);
    };
    initLoad();
  }, [fetchPageData]); // 补齐依赖 fetchPageData
  // 点击View More 加载下一页
  const handleViewMore = () => {
    const nextPage = page + 1;
    setPage(nextPage);
    fetchPageData(nextPage);
  };

  // 五星星星渲染
  const renderStars = (count: number) => {
    return Array.from({ length: count }).map((_, idx) => (
      <svg
        key={idx}
        className="w-4 h-4 text-green-600 inline-block"
        viewBox="0 0 24 24"
        fill="currentColor"
      >
        <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
      </svg>
    ));
  };

  return (
    <section className="py-6 px-4 pt-8">
      <h2 className="text-[clamp(1.5rem,4vw,2.2rem)] font-semibold mb-6">
        Recommended For You
      </h2>

      {/* 商品2列网格 */}
      <div className="grid grid-cols-2 gap-4">
        {productList.map((item) => (
          <div key={item.id} className="flex flex-col gap-3">
            {/* Next.Image 商品图容器 */}
            <div className="relative w-full aspect-[3/4] overflow-hidden rounded-md">
              <Image
                src={item.img}
                alt={item.title}
                fill
                sizes="(max-width:768px) 50vw, 33vw"
                className="object-cover"
              />
            </div>

            {/* 标题 */}
            <p className="text-sm text-gray-800 truncate">{item.title}</p>

            {/* 星级 + 评论数 */}
            <div className="flex items-center gap-1">
              {renderStars(item.star)}
              <span className="text-sm text-gray-600 ml-1 underline">
                {item.reviewCount}
              </span>
            </div>

            {/* 价格 + 购物车按钮 */}
            {/* <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <span className="text-xl font-bold text-black">
                  ${item.price}
                </span>
                <span className="text-sm text-gray-400 line-through">
                  ${item.originPrice}
                </span>
              </div>
              <button className="w-10 h-10 bg-emerald-600 rounded-lg flex items-center justify-center text-white">
                <svg
                  width="18"
                  height="18"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                >
                  <path d="M6 3h12M3 6h18l-2 11H5L3 6z" />
                  <circle cx="9" cy="20" r="1" />
                  <circle cx="15" cy="20" r="1" />
                </svg>
              </button>
            </div> */}
            {/* 价格 + 购物车图标 */}
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-1">
                <span className="font-semibold">${item.price}</span>
                <span className="text-xs text-gray-500 line-through">
                  ${item.originPrice}
                </span>
              </div>
              {/* 购物车图标 */}
              <OpenAddToCartModalButton
                productUrlKey={
                  "http://nshop.test/hd-transparent-deep-wave-&-curly-lace-frontal-closure-wig"
                }
                icon={
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="32"
                    height="32"
                    viewBox="0 0 32 32"
                    fill="none"
                  >
                    <rect
                      x="0"
                      y="0"
                      width="32"
                      height="32"
                      rx="8"
                      fill="#036141"
                    ></rect>
                    <path
                      stroke="rgba(255, 255, 255, 1)"
                      stroke-width="1.3333333333333333"
                      stroke-linejoin="round"
                      stroke-linecap="round"
                      d="M6.40039 7.79993L8.03372 7.79993L8.73372 10.5999M8.73372 10.5999L11.0671 19.9333L23.2004 19.9333L25.5337 10.5999L8.73372 10.5999Z"
                    ></path>
                    <ellipse
                      cx="11.066040515899658"
                      cy="23.199928283691406"
                      rx="1.4000248908996582"
                      ry="1.4000015258789062"
                      stroke="rgba(255, 255, 255, 1)"
                      stroke-width="1.3333333333333333"
                      stroke-linejoin="round"
                      stroke-linecap="round"
                    ></ellipse>
                    <ellipse
                      cx="23.1998291015625"
                      cy="23.199928283691406"
                      rx="1.4000244140625"
                      ry="1.4000015258789062"
                      stroke="rgba(255, 255, 255, 1)"
                      stroke-width="1.3333333333333333"
                      stroke-linejoin="round"
                      stroke-linecap="round"
                    ></ellipse>
                    <path
                      stroke="rgba(255, 255, 255, 1)"
                      stroke-width="1.3333333333333333"
                      stroke-linejoin="round"
                      stroke-linecap="round"
                      d="M15.2656 15.2665L18.999 15.2665"
                    ></path>
                    <path
                      stroke="rgba(255, 255, 255, 1)"
                      stroke-width="1.3333333333333333"
                      stroke-linejoin="round"
                      stroke-linecap="round"
                      d="M17.1348 17.1332L17.1348 13.3999"
                    ></path>
                  </svg>
                }
              />
            </div>
          </div>
        ))}
      </div>

      {/* View More 按钮：有下一页且非加载中显示 */}
      {hasMore && (
        <div className="flex justify-center mt-8">
          <button
            onClick={handleViewMore}
            disabled={loading}
            className="px-8 py-2 border border-black rounded-full text-base hover:bg-gray-100 transition disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {loading ? "Loading..." : "View More"}
          </button>
        </div>
      )}
    </section>
  );
}
