"use client";
import { getAPIAuth } from "@/services/apiservice";
import { TRANSACTION_HISTORY } from "@/utils/APIConstant";
import { useQuery } from "@tanstack/react-query";
import React, { useState, useEffect } from "react";
import { FaArrowUp, FaArrowDown } from "react-icons/fa";
import { useSelector } from "react-redux";

const TransactionHistory = () => {
  const [page, setPage] = useState(1);
  const perPage = 10;
  const [allTransactions, setAllTransactions] = useState([]);

  const Token = useSelector((state) => state?.userCredential?.token);
  const ProfileCredential = useSelector(
    (state) => state?.ProfileCredencial?.Credential
  );

  const { data, isFetching } = useQuery({
    queryKey: ["get-transaction-history", page],
    queryFn: async () => {
      const res = await getAPIAuth(
        `${TRANSACTION_HISTORY}?page=${page}&perPage=${perPage}&domain=medivora.com`,
        Token
      );
      return res.data;
    },
    enabled: !!Token,
  });

  useEffect(() => {
    if (data?.data?.documents) {
      const newData = data.data.documents;
      setAllTransactions((prev) => {
        // Prevent duplicates by checking if data for this page already exists
        const existingIds = new Set(prev.map((t) => t._id));
        const uniqueNew = newData.filter((t) => !existingIds.has(t._id));
        return [...prev, ...uniqueNew];
      });
    }
  }, [data]);

  const totalDocs = data?.data?.pagination?.totalChildrenCount || 0;
  const hasMore = allTransactions.length < totalDocs;

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 p-4 md:p-8 mt-9 md:pt-[90px] pt-[119px]">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="bg-white rounded-2xl shadow-lg p-6 mb-6">
          <div className="flex items-center justify-between mb-6">
            <div>
              <h1 className="text-3xl font-bold text-gray-800">
                Transaction History
              </h1>
              <p className="text-gray-500 mt-1">Track all your transactions</p>
            </div>

            <div className="px-4 py-2 bg-green-50 border border-green-200 rounded-xl">
              <p className="text-sm text-gray-600">Wallet Balance</p>
              <p className="text-xl font-bold text-green-600">
                ₹{ProfileCredential?.currentBalance || 0}
              </p>
            </div>
          </div>
        </div>

        {/* Transaction List */}
        <div className="space-y-3">
          {allTransactions?.map((transaction) => (
            <div
              key={transaction?._id}
              className="bg-white rounded-xl shadow-md hover:shadow-lg transition p-5 flex items-center justify-between"
            >
              <div className="flex items-center gap-4">
                <div
                  className={`w-12 h-12 rounded-full flex items-center justify-center ${
                    transaction?.type === "Cr" ? "bg-green-100" : "bg-red-100"
                  }`}
                >
                  {transaction.type === "Cr" ? (
                    <FaArrowDown className="text-green-600" size={24} />
                  ) : (
                    <FaArrowUp className="text-red-600" size={24} />
                  )}
                </div>
                <div>
                  <h4 className="font-semibold text-gray-800 text-lg">
                    {transaction?.remark}
                  </h4>
                  <p className="text-gray-400 text-xs mt-1">
                    {new Date(transaction?.createdAt).toLocaleString("en-IN", {
                      day: "2-digit",
                      month: "short",
                      year: "numeric",
                      hour: "2-digit",
                      minute: "2-digit",
                      hour12: true,
                    })}
                  </p>
                </div>
              </div>

              <div className="text-right">
                <p
                  className={`font-bold text-xl ${
                    transaction.type === "Cr"
                      ? "text-green-600"
                      : "text-red-600"
                  }`}
                >
                  {transaction.type === "Cr" ? "+" : "-"}₹
                  {String(transaction?.amount)?.toLocaleString("en-IN")}
                </p>
              </div>
            </div>
          ))}
        </div>

        {/* No Transactions */}
        {allTransactions.length === 0 && !isFetching && (
          <div className="bg-white rounded-xl shadow-md p-12 text-center mt-4">
            <p className="text-gray-500 text-lg">No transactions found</p>
          </div>
        )}

        {/* Load More Button */}
        {hasMore && (
          <div className="mt-6 flex justify-center">
            <button
              onClick={() => setPage(page + 1)}
              disabled={isFetching}
              className="px-6 py-2 bg-blue-600 text-white rounded-lg shadow hover:bg-blue-700 disabled:opacity-40"
            >
              {isFetching ? "Loading..." : "Load More"}
            </button>
          </div>
        )}

        {/* No More Data */}
        {!hasMore && allTransactions.length > 0 && (
          <p className="text-center text-gray-500 mt-4">No more transactions</p>
        )}
      </div>
    </div>
  );
};

export default TransactionHistory;
