"use client";
import React, { useEffect, useRef, useState } from "react";
import {
  fetchAffiliateAnalytics,
  fetchWithdrawBalance,
} from "@/app/lib/api/profile";

interface AffiliateRow {
  date: string;
  orderId: string;
  amount: string;
  status: "Paid" | "Pending" | "Cancelled";
}
import { useSelector } from "react-redux";
import { User } from "@/constants/types";
import { updateUser } from "@/app/store/authSlice";
import { updateSession } from "@/app/lib/api/inventory";
import { useAppDispatch } from "@/app/lib/hooks";
import AlertModal from "../ui/AlertModal";
interface AuthState {
  user: User; // adjust type as needed
  status: string;
}
type Props = {
  onRefData: (code: string | null, url: string | null) => void;
};

const Affiliate = ({ onRefData }: Props) => {
  const [availableBalance, setAvailableBalance] = useState<number>(0);

  const [referrals, setReferrals] = useState<string>("0");
  const [totalEarned, setTotalEarned] = useState<string>("$0");
  const [refCode, setRefCode] = useState<string | null>(null);
  const [refUrl, setRefUrl] = useState<string | null>(null);

  const user = useSelector((state: { auth: AuthState }) => state.auth.user);
  const status = useSelector(
    (state: { auth: AuthState }) => state?.auth?.status,
  );

  const [rows, setRows] = useState<AffiliateRow[]>([]);
  const [page, setPage] = useState(1);
  const pageSize = 7;
  const totalPages = Math.max(1, Math.ceil(rows.length / pageSize));
  const paginatedRows = rows.slice((page - 1) * pageSize, page * pageSize);

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [withdrawBalanceLoading, setWithdrawBalanceLoading] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [modalType, setModalType] = useState<"success" | "error">("success");
  const [modalMsg, setModalMsg] = useState("");
  const dispatch = useAppDispatch();
  const hasFetched = useRef(false); // avoid double-call in StrictMode
  const goToPage = (num: number) => {
    if (num >= 1 && num <= totalPages) setPage(num);
  };

  const getBalanceNumber = () =>
    Number(String(availableBalance).replace(/[^0-9.]/g, "")) || 0;

  const statusClasses = (status: AffiliateRow["status"]) => {
    switch (status) {
      case "Paid":
        return "bg-[var(--color-parrot)]";
      case "Pending":
        return "bg-[#FFB020] text-black";
      case "Cancelled":
        return "bg-[#FF4B4B] text-white";
    }
  };

  const getWithdrawBalance = async () => {
    if (availableBalance <= 0) {
      setModalType("error");
      setModalMsg("No balance available to withdraw.");
      setModalOpen(true);
      return;
    }

    setWithdrawBalanceLoading(true);
    try {
      const res = await fetchWithdrawBalance(user.userId, user.token);

      if (res.resp === "success") {
        setModalType("success");
        setModalMsg("Balance withdrawn successfully.");
        setModalOpen(true);

        setAvailableBalance(0);

        dispatch(updateUser({ coins: res?.coins, gems: res?.gems }));
        await updateSession({ coins: res?.coins, gems: res?.gems });
      }
    } catch (e: any) {
      console.log(e);
    }
  };

  useEffect(() => {
    onRefData(refCode, refUrl);
  }, [refCode, refUrl, onRefData]);

  useEffect(() => {
    // getWithdrawBalance();
    const loadAffiliate = async () => {
      if (hasFetched.current) return;
      hasFetched.current = true;

      try {
        setLoading(true);
        setError(null);

        const json = await fetchAffiliateAnalytics(user.userId, user.token);

      
        const data = json.data;

        // Top summary
        setAvailableBalance(Number(data.balance ?? 0));
        setReferrals(String(data.referal ?? 0));
        setTotalEarned(`$${data.paid ?? "0"}`);
        setRefCode(data.ref_code);
        setRefUrl(data.url);

        // Table rows from data.History
        const mapped: AffiliateRow[] = (data.History || []).map((h: any) => {
          const rawStatus = String(h.status || "Pending").toLowerCase();
          let status: AffiliateRow["status"] = "Pending";
          if (rawStatus.includes("paid")) status = "Paid";
          else if (rawStatus.includes("cancel")) status = "Cancelled";

          return {
            date: h.date ?? "",
            orderId: h.orderId ?? h.order ?? "",
            amount: h.amount ?? "$0",
            status,
          };
        });

        setRows(mapped);
        setPage(1);
      } catch (err: any) {
        setError(err.message || "Something went wrong");
      } finally {
        setLoading(false);
      }
    };

    loadAffiliate();
  }, []);

  return (
    <div className="text-white font-onest">
      {/* Top cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-2 md:gap-3 2xl:gap-6 mb-2 md:mb-4">
        {/* Available Balance */}
        <div className="bg-(--color-naviBlue) px-3 xl:px-6 py-5">
          <p className="text-xs md:text-sm 2xl:text-base font-semibold tracking-wide mb-4 uppercase">
            Available Balance
          </p>

          <div className="flex items-center gap-2 xl:gap-3">
            <div className="bg-black px-4 py-2 2xl:py-3 min-w-30 text-xs md:text-lg 2xl:text-2xl font-extrabold">
              ${availableBalance}
            </div>
            <button
              onClick={() => getWithdrawBalance()}
              className="px-5 py-2 border border-white text-xs md:text-sm 2xl:text-base hover:bg-(--color-gray) transition"
            >
              Withdraw
            </button>
          </div>
        </div>

        {/* Referrals */}
        <div className="bg-(--color-naviBlue) px-3 xl:px-6 py-5 ">
          <p className="text-xs md:text-sm 2xl:text-base font-semibold tracking-wide mb-4 uppercase">
            Referrals
          </p>

          <div className="bg-black inline-block px-4 py-2 2xl:py-3 min-w-30 text-xs md:text-lg 2xl:text-2xl font-extrabold">
            {referrals}
          </div>
        </div>

        {/* Total Earned */}
        <div className="bg-(--color-naviBlue) px-3 xl:px-6 py-5 ">
          <p className="text-xs md:text-sm 2xl:text-base font-semibold tracking-wide mb-4 uppercase">
            Total Earned
          </p>

          <div className="bg-black inline-block px-4 py-2 2xl:py-3 min-w-30 text-xs md:text-lg 2xl:text-2xl font-extrabold">
            {totalEarned}
          </div>
        </div>
      </div>

      {/* Loading / error / table */}
      {loading && (
        <div className="flex w-full h-40 items-center justify-center">
          <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
        </div>
      )}

      {error && (
        <div className="py-6 text-center text-sm text-red-400">{error}</div>
      )}

      <div className="overflow-x-auto bg-[var(--color-naviBlue)]">
        <table className="w-full min-w-[700px] text-left">
          <thead>
            <tr className="text-sm md:text-base font-bold font-onest bg-[var(--color-darkBlue)]">
              <th className="py-3 md:py-4 px-4 md:px-8">Date</th>
              <th className="py-3 md:py-4 px-4 md:px-8">Order</th>
              <th className="py-3 md:py-4 px-4 md:px-8">Amount</th>
              <th className="py-3 md:py-4 px-4 md:px-8">Status</th>
            </tr>
          </thead>

          <tbody>
            {!loading &&
              !error &&
              paginatedRows.map((row, idx) => (
                <tr
                  key={row.orderId || `${row.date}-${idx}`}
                  className={`text-sm md:text-base font-medium font-onest ${
                    idx % 2 === 1 ? "bg-[#111722]" : ""
                  } hover:bg-(--color-gray)/30 transition`}
                >
                  <td className="py-3 md:py-4 px-4 md:px-8">{row.date}</td>
                  <td className="py-3 md:py-4 px-4 md:px-8">{row.orderId}</td>
                  <td className="py-3 md:py-4 px-4 md:px-8">{row.amount}</td>
                  <td className="py-3 md:py-4 px-4 md:px-8">
                    <span
                      className={`px-3 py-1 text-[10px] md:text-xs uppercase tracking-wide rounded-sm ${statusClasses(
                        row.status,
                      )}`}
                    >
                      {row.status}
                    </span>
                  </td>
                </tr>
              ))}

            {!loading && !error && paginatedRows.length === 0 && (
              <tr>
                <td
                  colSpan={4}
                  className="py-10 text-center text-sm md:text-base text-(--color-naturalGray)"
                >
                  No affiliate transactions yet.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      <div className="flex font-onest justify-center items-center gap-3 m-6">
        <button
          onClick={() => goToPage(page - 1)}
          disabled={page === 1}
          className="rounded-full w-[34px] h-[34px] flex justify-center items-center bg-[var(--color-gray)] hover:bg-[var(--color-gray)] disabled:opacity-40"
        >
          <img src="/images/profile/left.svg" alt="Previous" />
        </button>

        <div className="flex gap-2 text-sm">
          {[...Array(totalPages)].map((_, i) => {
            const pg = i + 1;

            if (pg === 1 || pg === totalPages || Math.abs(pg - page) <= 1) {
              return (
                <button
                  key={pg}
                  onClick={() => goToPage(pg)}
                  className={`px-3 py-1 rounded transition-transform ${
                    pg === page
                      ? "scale-115 text-white"
                      : "text-(--color-naturalGray)"
                  }`}
                >
                  {pg}
                </button>
              );
            }

            if (pg === page - 2 || pg === page + 2) {
              return (
                <span key={`ellipsis-${pg}`} className="px-2 text-gray-400">
                  ...
                </span>
              );
            }

            return null;
          })}
        </div>

        <button
          onClick={() => goToPage(page + 1)}
          disabled={page === totalPages}
          className="flex justify-center items-center w-8.5 h-[34px] rounded-full bg-[var(--color-gray)] hover:bg-[var(--color-gray)] disabled:opacity-40"
        >
          <img src="/images/profile/right.svg" alt="Next" />
        </button>
      </div>
      <AlertModal
        open={modalOpen}
        type={modalType}
        message={modalMsg}
        onClose={() => setModalOpen(false)}
      />
    </div>
  );
};

export default Affiliate;
