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

export default function GetPoints() {
  const [taskData, setTaskData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    const fetchRewardPointsHistory = async () => {
      try {
        setLoading(true);
        const res = await clientFetch("/api/customer/reward-points/follow-status");
      
        setTaskData(res.data.data);
        console.log("积分任务数据：", res.data.data);
      } catch (error) {
        console.error("获取任务状态失败：", error);
      } finally {
        setLoading(false);
      }
    };
    fetchRewardPointsHistory();
  }, []);

  function canTriggerTask(item: (typeof earnPointsItems)[0]) {
  
    if (!taskData) return false;

    const { type } = item;
    const { browsed_product_ids, platforms } = taskData;

    if (!type) return true;

   
    if (browsed_product_ids.includes(type)) {
      return false;
    }

    const platform = platforms.find((p: any) => p.code === type);
    if (platform) {
      return !platform.followed;
    }

    return true;
  }

  
  const handleClaimPoints = async (item: any) => {
 
    if (!canTriggerTask(item)) return;

    try {
      console.log("触发领取积分，任务类型：", item.type);
      
      // const getpointsres = await clientFetch("/api/customer/reward-points/follow", {  
      //   method: "POST",
      //   body: JSON.stringify({ platform: item.type }),
      // });
      // 这个浏览获取积分接口后面放到列表页去调
      const getpointsres = await clientFetch("/api/customer/reward-points/browse-product", {  
        method: "POST",
        body: JSON.stringify({ categorys: item.type }),
      });
      if(getpointsres.data.success){
        alert("Points claimed successfully!");
      }
      
      const res = await clientFetch("/api/customer/reward-points/follow-status");
      setTaskData(res.data.data);
    } catch (err) {
      console.error("领取失败", err);
      alert("Failed to claim points");
    }
  };

  const earnPointsItems = [
    {
      title: "Share a plain text review",
      desc: "To Get 50 points",
      points: "",
      type: "",
    },
    {
      title: "Share your wig review with photos/videos",
      desc: "To Get 100 Points",
      points: "",
      type: "",
    },
    {
      title: "Log In Our Website",
      desc: "Every Day To Get Points",
      points: "",
      type: "",
    },
    {
      title: "Browse New Arrival Page ≥ 15 Seconds",
      desc: "To Get 10 Points",
      points: "",
      type: "aaa",
    },
    {
      title: "Browse HD Lace Wigs ≥ 15 Seconds",
      desc: "To Get 10 Points",
      points: "",
      type: "ccc",
    },
    {
      title: "Browse Ready To Go Wigs ≥ 15 Seconds",
      desc: "To Get 10 Points",
      points: "",
      type: "bbbb",
    },
    {
      title: "Follow Our Instagram Account",
      desc: "To Get 20 Points",
      points: "",
      type: "ig",
    },
    {
      title: "Follow Our Facebook Account",
      desc: "To Get 20 Points",
      points: "",
      type: "fb",
    },
    {
      title: "Follow Our Youtube Channel",
      desc: "To Get 20 Points",
      points: "",
      type: "ytb",
    },
    {
      title: "Follow Our Tiktok Account",
      desc: "To Get 20 Points",
      points: "",
      type: "tt",
    },
  ];

  return (
    <div className="space-y-2">
      {loading ? (
        <div>Loading tasks...</div>
      ) : (
        earnPointsItems.map((item, index) => {
          const canClick = canTriggerTask(item);
          return (
            <div
              key={index}
              className="h-15.5 flex items-center justify-between bg-[#F8F8F8] p-2.5 rounded-md "
            >
              <div>
                <h3 className="font-medium text-black">{item.title}</h3>
                {item.desc && <p className="text-sm text-gray-500">{item.desc}</p>}
              </div>
              <div className="flex items-center gap-6">
                {item.points && (
                  <span className="font-medium">{item.points}</span>
                )}
                <button
                  onClick={() => handleClaimPoints(item)}
                  disabled={!canClick}
                  className={`transition-colors ${
                    canClick ? "text-black" : "text-gray-300 cursor-not-allowed"
                  }`}
                >
                  <svg
                    viewBox="0 0 24 24"
                    width="16"
                    height="16"
                    fill="currentColor"
                  >
                    <path d="M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z" />
                  </svg>
                </button>
              </div>
            </div>
          );
        })
      )}
    </div>
  );
}