"use client";
import React, { useState, useEffect, useRef, useCallback } from "react";
import Link from "next/link";
import { clientFetch } from "@/lib/restApiClient";

// 👉 你的 TS 类型（正确）
interface ListDates {
  amount: number;
  balance: number;
  created_at: string;
  detail: string;
  expired_day: number;
  expired_time: string | null;
  id: number;
  order_id: number | null;
  remaining_points: number;
  status: number;
  status_text: string;
  type: number;
  type_text: string;
}

const PointsDetails = () => {
  // 状态
  const [activeTab, setActiveTab] = useState<string>(""); // earned / redeemed / 空
  const [listData, setListData] = useState<ListDates[]>([]);
  const [page, setPage] = useState<number>(1);
  const [loading, setLoading] = useState<boolean>(false);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const listRef = useRef<HTMLDivElement>(null);
  const PAGE_SIZE = 10;

  // ==============================================

  const loadData = useCallback(async (currentPage: number, tab: string) => {
    setLoading(true);
    try {
      const resp = await clientFetch(
        `/api/customer/reward-points/history?page=${currentPage}&per_page=${PAGE_SIZE}&amountType=${tab}`,
      );

      console.log("接口返回：", resp);

      if (resp.status === 200) {
        const formData = resp.data?.data || resp.data || { history: [] };
        const newList = formData.history || [];
        // 测试数据
        //  const testList = [...newList, ...newList, ...newList, ...newList];
        // 分页判断：如果返回不足10条 = 没有更多
        if (newList.length < PAGE_SIZE) {
          setHasMore(false);
        } else {
          setHasMore(true);
        }

        if (currentPage === 1) {
          setListData(newList);
        } else {
          setListData((prev) => [...prev, ...newList]);
        }
      }
    } catch (err) {
      console.error("加载失败：", err);
    } finally {
      setLoading(false);
    }
  }, []);

  const loadMore = useCallback(() => {
    console.log("loading:", loading, "hasMore:", hasMore);

    if (loading || !hasMore) return;
    const nextPage = page + 1;
    loadData(nextPage, activeTab);
    setPage(nextPage);
  }, [loading, hasMore, page, activeTab, loadData]);

  useEffect(() => {
    // 封装内部异步函数，规范写法
    const initLoad = async () => {
      setListData([]); // 切换时清空列表
      loadData(1, activeTab);
      setPage(1);
    };
    initLoad();
  }, [activeTab]);

  useEffect(() => {
    const container = listRef.current;
    const handleScroll = () => {
      // console.log("container:",container,"container.scrollTop:",container.scrollTop,"container.clientHeight:",container.clientHeight,"container.scrollHeight:",container.scrollHeight);

      if (!container) return;
      if (
        container.scrollTop + container.clientHeight >=
        container.scrollHeight - 20
      ) {
        loadMore();
      }
    };

    container?.addEventListener("scroll", handleScroll);
    return () => container?.removeEventListener("scroll", handleScroll);
  }, [loadMore]);

  const clickActiveTab = (tab: string) => {
    setActiveTab(tab);
  };

  return (
    <div className="min-h-screen bg-white">
      {/* 顶部 */}
      <div className="sticky top-0 z-10 bg-white border-b border-gray-100 py-4 px-4 flex items-center">
        <Link href={"/customer/account/mypoints"} className="mr-4">
          <svg viewBox="0 0 24 24" width="20" height="20" fill="black">
            <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" />
          </svg>
        </Link>
        <h1 className="text-xl font-bold text-black">Points Details</h1>
      </div>

      {/* Tab */}
      <div className="flex border-b border-gray-200">
        <button
          onClick={() => clickActiveTab("")}
          className={`px-6 py-3 font-medium text-sm ${
            activeTab === "" ? "bg-black text-white" : "bg-white text-gray-600"
          }`}
        >
          ALL
        </button>
        <button
          onClick={() => clickActiveTab("earned")}
          className={`px-6 py-3 font-medium text-sm ${
            activeTab === "earned"
              ? "bg-black text-white"
              : "bg-white text-gray-600"
          }`}
        >
          REWARDED
        </button>
        <button
          onClick={() => clickActiveTab("redeemed")}
          className={`px-6 py-3 font-medium text-sm ${
            activeTab === "redeemed"
              ? "bg-black text-white"
              : "bg-white text-gray-600"
          }`}
        >
          USED
        </button>
      </div>

      {/* 列表 */}
      <div ref={listRef} className="h-[calc(100vh-120px)] overflow-y-auto">
        {listData.length > 0 ? (
          <div className="divide-y divide-gray-100">
            {listData.map((item) => (
              <div key={item.id} className="px-4 py-4">
                <div className="flex justify-between items-start">
                  <div>
                    <h3 className="text-base font-medium text-black">
                      {item.detail}
                    </h3>
                    <p className="text-xs text-gray-500 mt-1">
                      {item.created_at}
                    </p>
                  </div>
                  <div className="text-right">
                    <p
                      className={`text-base font-medium ${item.amount >= 0 ? "text-green-600" : "text-black"}`}
                    >
                      {item.amount >= 0 ? `+${item.amount}` : item.amount}{" "}
                      Points
                    </p>
                    <p className="text-xs text-gray-500 mt-1">
                      My points: {item.balance}
                    </p>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div className="flex items-center justify-center h-32">
            <p className="text-gray-500 text-sm">NO DATA</p>
          </div>
        )}

        {/* 加载提示 */}
        <div className="px-4 py-3 text-center text-sm">
          {loading && <p className="text-gray-500">Loading...</p>}
          {!loading && !hasMore && listData.length > 0 && (
            <p className="text-gray-500">NO MORE DATA</p>
          )}
        </div>
      </div>
    </div>
  );
};

export default PointsDetails;
