"use client";

import React, { useEffect, useRef, useState } from "react";
import { fetchBalanceHistory } from "@/app/lib/api/profile";

import { useSelector } from "react-redux";
import { User } from "@/constants/types";
interface AuthState {
  user: User; // adjust type as needed
  status: string;
}

type HistoryItem = {
  // ⚠️ adjust these to match your real API fields
  id: number | string;
  date: string; // e.g. "23-07-2025 12:45" or ISO string
  type: string; // "Deposit" / "Withdraw" etc.
  amount: number; // in your currency
  handler: string; // e.g. "Credit Card"
};

const Balance = ({ onTotals }: any) => {
  const [history, setHistory] = useState<HistoryItem[]>([]);
  const [balance, setBalance] = useState<number>(0);
  const [deposit, setDeposit] = useState<number>(0);
  const [withdraw, setWithdraw] = useState<number>(0);
  const [total, setTotal] = useState<number>(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const user = useSelector((state: { auth: AuthState }) => state.auth.user);
  const pageSize = 7;

  const totalPages = Math.ceil(history.length / pageSize) || 1;

  const paginatedData = history.slice((page - 1) * pageSize, page * pageSize);

  const goToPage = (num: number) => {
    if (num >= 1 && num <= totalPages) setPage(num);
  };
  const hasFetched = useRef(false);

  useEffect(() => {
    const load = async () => {
      if (hasFetched.current) return;
      hasFetched.current = true;

      try {
        setLoading(true);

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

        if (json.resp !== "success") {
          throw new Error("Backend error");
        }

        const data = json.data;

        setBalance(data.balance);
        setDeposit(data.deposit);
        setWithdraw(data.withdraw);
        setTotal(data.total);

        setHistory(
          data.history.map((h: any) => ({
            id: h.id,
            date: h.date,
            type: h.type,
            amount: h.amount,
            handler: h.handler,
          })),
        );
      } catch (err: any) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    load();
  }, []);

  useEffect(() => {
    onTotals(deposit, withdraw);
  }, [deposit, withdraw, onTotals]);

  return (
    <div className="overflow-x-auto nice-scrollbar bg-[var(--color-naviBlue)] text-white">
      {error && (
        <div className="p-6 text-center text-sm font-onest text-red-400">
          {error}
        </div>
      )}

      {loading ? (
        <div className="flex w-full h-[160px] items-center justify-center">
          <div className="w-8 h-8 border-4 border-white/20 border-t-white rounded-full animate-spin" />
        </div>
      ) : (
        <>
          {/* Table */}
          <table className="w-full min-w-200 text-left ">
            <thead>
              <tr className="text-sm md:text-base font-bold font-onest bg-[#121924]">
                <th className="py-3 md:py-5 px-4 md:px-8">Date</th>
                <th className="py-3 md:py-5 px-4 md:px-8">ID</th>
                <th className="py-3 md:py-5 px-4 md:px-8">Type</th>
                <th className="py-3 md:py-5 px-4 md:px-8">Amount</th>
                <th className="py-3 md:py-5 px-4 md:px-8">Handler</th>
              </tr>
            </thead>

            <tbody>
              {!loading && !error && history.length === 0 ? (
                <tr>
                  <td
                    colSpan={5}
                    className="p-6 text-center  text-sm font-onest text-gray-300"
                  >
                    No transactions yet.
                  </td>
                </tr>
              ) : (
                paginatedData.map((item, index) => (
                  <tr
                    key={item.id ?? index}
                    className={`text-sm md:text-base font-medium font-onest ${
                      index % 2 === 1 ? "bg-[#121924]" : ""
                    } hover:bg-[var(--color-gray)]/30 transition`}
                  >
                    <td className="py-3 md:py-5 px-4 md:px-8">{item.date}</td>
                    <td className="py-3 md:py-5 px-4 md:px-8">{item.id}</td>
                    <td className="py-3 md:py-5 px-4 md:px-8">{item.type}</td>
                    <td className="py-3 md:py-5 px-4 md:px-8">
                      $
                      {item.amount?.toFixed
                        ? item.amount.toFixed(2)
                        : item.amount}
                    </td>
                    <td className="py-3 md:py-5 px-4 md:px-8">
                      {item.handler}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>

          {/* 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="" />
            </button>

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

                // show only first, last, current, and neighbors
                if (pg === 1 || pg === totalPages || Math.abs(pg - page) <= 1) {
                  return (
                    <button
                      key={pg}
                      onClick={() => goToPage(pg)}
                      className={`px-3 py-1 rounded ${
                        pg === page
                          ? "scale-115 text-white"
                          : " text-[var(--color-naturalGray)]"
                      }`}
                    >
                      {pg}
                    </button>
                  );
                }

                // ellipsis
                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-[34px] h-[34px] rounded-full bg-[var(--color-gray)] hover:bg-[var(--color-gray)] disabled:opacity-40"
            >
              <img src="/images/profile/right.svg" alt="" />
            </button>
          </div>
        </>
      )}
    </div>
  );
};

export default Balance;
