"use client";
import { useEffect, useState, useRef, useCallback } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { useSearchParams } from "next/navigation";

// 模拟订单数据
const mockOrders = [
  {
    id: 600217097,
    date: "3/4/2026",
    status: "Processing",
    items: [
      {
        name: "Highlight Wigs For Women Headband Wigs with Blonde Highlights",
        specs: "10, #022, Straight, 5 Free Headbands",
        price: "88 points + $154.05x1",
        image:"",
      },
    ],
    progress: "Preparing Order",
    total: "88 Points + $158.67",
  },
  {
    id: 100055662,
    date: "3/3/2026",
    status: "Processing",
    items: [
      {
        name: "Alipearl Lace Front Wig 180% Density Body Wave Human Hair Wigs Pre...",
        specs: "10+180%, Medium, No Adjustable Band",
        price: "$128.82x1",
        image:"",
      },
    ],
    progress: "Preparing Order",
    total: "$132.68",
  },
  {
    id: 600217055,
    date: "3/3/2026",
    status: "Processing",
    items: [
      {
        name: "3 Bundles Deep Wave Hair With 4*4 Lace Closure Alipearl Brazilian Hair",
        specs: "8 8 8, Free Part, 8",
        price: "$142.14x1",
        image:"",
      },
      {
        name: "Princess Braids Wig Blonde Barbie Pre-Styled Highlight Wig 13×4 Front Wig",
        specs: "12",
        price: "$279.32x1",
        image:
          "https://cdn.alipearlhair.com/media/catalog/product/cache/6/thumbnail/750x1000/9df78eab33525d08d6e5fb8d27136e95/b/o/body_wave_lace_front_wig_2.jpg", // 替换为实际图片路径
      },
      {
        name: "Deep Wave Wig 100 Human Hair Swiss Lace Wig Lace Front Wig",
        specs: "10, Medium, 100%",
        price: "$252.00x1",
         image:"",
      },
      {
        name: "Braids Wig Blonde Barbie Pre-Styled Highlight Wig 13×4 Front Wig",
        specs: "12",
        price: "6000 points + $279.32x1",
        image:
          "https://cdn.alipearlhair.com/media/catalog/product/cache/6/thumbnail/750x1000/9df78eab33525d08d6e5fb8d27136e95/b/o/body_wave_lace_front_wig_2.jpg", // 替换为实际图片路径
      },
      {
        name: "random free wigs-2",
        specs: "",
        price: "$0.00x1",
        image:"",
      },
    ],
    progress: "Preparing Order",
    discount: "-$80.00",
    total: "$872.78",
  },
];

// 标签列表
const tabs = [
  { key: "all", label: "All" },
  { key: "processing", label: "Processing" },
  { key: "complete", label: "Complete" },
  { key: "Payment", label: "Payment Review" }, // 补充模拟标签，测试滚动
];

export default function OrderHistory() {
  const router = useRouter();
  const [activeTab, setActiveTab] = useState("all");
  const [filteredOrders, setFilteredOrders] = useState(mockOrders);
  // 组件内新增
  const searchParams = useSearchParams();
  const lastHashRef = useRef<string>("");
  // 模拟接口请求：不同标签传不同参数
  const fetchOrders = (tabKey: string) => {
    console.log("请求接口参数：", tabKey); // 实际项目替换为真实接口调用
    // 这里简化逻辑，仅过滤Processing状态（实际接口返回对应数据）
    if (tabKey === "processing") {
      setFilteredOrders(mockOrders.filter((o) => o.status === "Processing"));
    } else if (tabKey === "complete") {
      setFilteredOrders([]); // 模拟无完成订单
    } else {
      setFilteredOrders(mockOrders);
    }
  };
  // 把更新状态+请求的逻辑抽离，Effect 只调用这个函数，不直接写setState
  const updateTabByHash = useCallback(
    (hashKey: string) => {
      const validTab = tabs.find((t) => t.key === hashKey.toLowerCase());
      const targetKey = validTab ? validTab.key : "all";
      // setState 全部放在回调函数里，不在 useEffect 顶层同步执行
      setActiveTab(targetKey);
      fetchOrders(targetKey);
    },
    [tabs, fetchOrders],
  );

  // 监听哈希变化，Effect 内部无任何直接setState
  useEffect(() => {
    const currentHash = searchParams.get("") || "all";
    // 对比上一次缓存的hash，避免重复执行
    if (lastHashRef.current !== currentHash) {
      lastHashRef.current = currentHash;
      // 仅调用抽离好的函数，Effect内部没有setActiveTab
      updateTabByHash(currentHash);
    }
  }, [searchParams, updateTabByHash]);

  // 点击标签切换
  const handleTabClick = (tabKey: string) => {
    // window.location.hash = tabKey; // 更新URL哈希
    router.push(`#${tabKey}`, { scroll: false });
    setActiveTab(tabKey);
    fetchOrders(tabKey);
  };

  return (
    <>
      <div className="min-h-screen bg-gray-50">
        {/* 顶部返回栏 + 标题 */}
        <Link href={"/customer/account"} className="sticky top-0 z-20 bg-white px-4 py-3 border-b flex justify-between items-center w-full">
          <button className="text-black text-xl mr-4">
            <svg
              className="w-6 h-6"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="111033"
              width="200"
              height="200"
            >
              <path
                d="M391.466667 512l339.882666-339.882667a46.592 46.592 0 1 0-65.877333-65.877333L292.693333 479.061333a46.592 46.592 0 0 0 0 65.877334l372.821334 372.821333a46.592 46.592 0 1 0 65.877333-65.877333L391.466667 512z"
                p-id="111034"
              ></path>
            </svg>
          </button>
          <h1 className="text-xl font-bold mx-auto">Orders</h1>
          <div className="w-6"></div>
        </Link>

        {/* 标签栏（固定顶部 + 横向滚动） */}
        <div className="sticky top-14 z-10 bg-white px-4 py-2 border-b">
          <div className="flex items-center space-x-6 overflow-x-auto pb-1 scrollbar-hide">
            {tabs.map((tab) => (
              <button
                key={tab.key}
                onClick={() => handleTabClick(tab.key)}
                className={`whitespace-nowrap py-1 px-3 rounded-full text-sm font-medium transition-colors
                ${
                  activeTab === tab.key
                    ? "bg-black text-white"
                    : "text-gray-600 hover:bg-gray-100"
                }`}
              >
                {tab.label}
              </button>
            ))}
          </div>
        </div>

        {/* 订单列表 */}
        <div className="px-4 py-3">
          {filteredOrders.length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              No orders found
            </div>
          ) : (
            filteredOrders.map((order) => (
              <div
                key={order.id}
                className="bg-white rounded-lg p-4 mb-4 border"
              >
                {/* 订单状态 + 编号 + 日期 */}
                <div className="mb-3">
                  <p className="font-medium text-gray-800">• {order.status}</p>
                  <div className="flex justify-between text-sm text-gray-600 mt-1">
                    <span>Order Number: {order.id}</span>
                    <span>Date: {order.date}</span>
                  </div>
                </div>

                {/* 订单商品列表 */}
                <div className="mb-4 space-y-3">
                  {order.items.map((item, idx) => (
                    <div key={idx} className="flex gap-3">
                      {/* 商品图片（有则显示，无则占位） */}
                      {item.image ? (
                        <img
                          src={item.image}
                          alt={item.name}
                          className="w-22.5 h-22.5 object-cover rounded"
                        />
                      ) : (
                        <div className="w-22.5 h-22.5 bg-gray-100 rounded"></div>
                      )}
                      {/* 商品信息 */}
                      <div className="flex-1">
                        <p className="text-sm text-gray-800 line-clamp-2">
                          {item.name}
                        </p>
                        {item.specs && (
                          <p className="text-xs text-gray-500 mt-1">
                            {item.specs}
                          </p>
                        )}
                        <p className="text-xs text-gray-600 mt-1">
                          {item.price}
                        </p>
                      </div>
                    </div>
                  ))}
                </div>

                {/* 订单进度条 */}
                <Link
                  href={`/customer/order/track/order_id/${order.id}`}
                  className="mb-4 h-8 bg-gray-100 rounded-full h-2 flex items-center px-2"
                >
                  <span className="ml-2 text-xs text-gray-700 flex-1 flex justify-between">
                    {order.progress}
                    <span>
                      <svg
                        className="w-4 h-4"
                        viewBox="0 0 1024 1024"
                        version="1.1"
                        xmlns="http://www.w3.org/2000/svg"
                        p-id="3784"
                        width="200"
                        height="200"
                      >
                        <path
                          d="M761.056 532.128c0.512-0.992 1.344-1.824 1.792-2.848 8.8-18.304 5.92-40.704-9.664-55.424L399.936 139.744a48 48 0 0 0-65.984 69.76l316.96 299.84L335.2 813.632a48 48 0 0 0 66.624 69.12l350.048-337.376c0.672-0.672 0.928-1.6 1.6-2.304 0.512-0.48 1.056-0.832 1.568-1.344 2.72-2.848 4.16-6.336 6.016-9.6z"
                          p-id="3785"
                        ></path>
                      </svg>
                    </span>
                  </span>
                </Link>

                {/* 折扣 + 总计 + 操作按钮 */}
                <div className="text-right text-sm">
                  {order.discount && (
                    <p className="text-red-500 flex items-center justify-between">
                      <span>Discount</span> <span>{order.discount}</span>
                    </p>
                  )}
                  <p className="font-bold mt-1 flex items-center justify-between">
                    <span>
                      Order Total ({order.items.length} item
                      {order.items.length > 1 ? "s" : ""})
                    </span>{" "}
                    <span>{order.total}</span>
                  </p>

                  <div className="flex justify-between mt-3">
                    <Link
                      href={`/customer/order/view/order_id/${order.id}`}
                      className="text-black-600 text-sm underline"
                    >
                      View Order
                    </Link>
                    <Link
                      href={`/customer/order/track/order_id/${order.id}`}
                      // state={{
                      //   addressData: {
                      //     /* 你的地址对象 */
                      //   },
                      // }}
                      className="border border-gray-300 rounded-full px-4 py-1 text-sm text-gray-800 hover:bg-gray-50"
                    >
                      Track Order
                    </Link>
                  </div>
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </>
  );
}
