"use client";

import React, { useCallback, useEffect, useRef } from "react";
import { usePathname } from "next/navigation";
import { PaginatedData } from "@/types/common.type";
import { TransactionRow } from "./elements/transactionRow";
import { Transaction } from "../../types/transaction.type";
import { Typography } from "@/components/atoms/typogrpahy";
import { History } from "lucide-react";
import { useTransactions } from "../../hooks/useTransaction";
import { shouldLoadMoreTransactions } from "./scrollObserver";

const HISTORY_DEBUG_PREFIX = "[wallet-history]";

function historyDebug(...args: unknown[]) {
  if (process.env.NODE_ENV !== "production") {
    console.debug(HISTORY_DEBUG_PREFIX, ...args);
  }
}

interface WalletHistorySectionProps {
  paginatedTransactions: PaginatedData<Transaction>;
}

export const WalletHistorySection: React.FC<WalletHistorySectionProps> = ({
  paginatedTransactions,
}) => {
  const pathname = usePathname();
  const { transactions, loading, error, hasMore, loadMore, refetch } = useTransactions({
    initialData: paginatedTransactions,
  });

  useEffect(() => {
    historyDebug("state", {
      transactionCount: transactions.length,
      loading,
      hasMore,
      error,
      initialCount: paginatedTransactions.data.length,
      initialPagination: paginatedTransactions.pagination ?? null,
    });
  }, [transactions.length, loading, hasMore, error, paginatedTransactions]);

  // Refetch when user returns to wallet page (mount = navigate back, or visibility = tab focus)
  useEffect(() => {
    refetch();
  }, []);

  useEffect(() => {
    const onVisibility = () => {
      if (document.visibilityState === "visible" && pathname === "/wallet") {
        refetch();
      }
    };
    document.addEventListener("visibilitychange", onVisibility);
    return () => document.removeEventListener("visibilitychange", onVisibility);
  }, [pathname, refetch]);
  const transactionListRef = useRef<HTMLDivElement | null>(null);
  const handleTransactionListScroll = useCallback(
    (event: React.UIEvent<HTMLDivElement>) => {
      const container = event.currentTarget;
      const shouldLoad = shouldLoadMoreTransactions({
        scrollTop: container.scrollTop,
        clientHeight: container.clientHeight,
        scrollHeight: container.scrollHeight,
        hasMore,
        loading,
      });

      historyDebug("scroll", {
        scrollTop: Math.round(container.scrollTop),
        clientHeight: container.clientHeight,
        scrollHeight: container.scrollHeight,
        distanceToBottom: Math.max(
          0,
          Math.round(container.scrollHeight - (container.scrollTop + container.clientHeight)),
        ),
        hasMore,
        loading,
        shouldLoad,
      });

      if (shouldLoad) {
        void loadMore();
      }
    },
    [hasMore, loading, loadMore],
  );

  return (
    <div className="w-full bg-white dark:bg-gray-800 rounded-lg shadow-md">
      {/* Header */}
      <div className="flex items-center p-6 pb-4 border-b border-gray-200 dark:border-gray-700 space-x-2">
        <History className="text-gray-500 dark:text-gray-400 w-5 h-5 sm:w-6 sm:h-6" />
        <Typography
          variant="s1"
          className="font-bold text-gray-800 dark:text-gray-100 text-sm sm:text-base"
        >
          Recent History
        </Typography>
      </div>

      {/* Transaction List with Status Messages Inside Scroll */}
      <div className="p-4 sm:p-6 pt-4">
        <div
          ref={transactionListRef}
          onScroll={handleTransactionListScroll}
          className="max-h-96 overflow-y-auto space-y-2 pr-2"
          style={{ scrollbarWidth: "thin", scrollbarColor: "rgba(156, 163, 175, 0.5) transparent" }}
        >
          {transactions?.length > 0 ? (
            <>
              {transactions.map((transaction: Transaction, index: number) => {
                return (
                  <div key={transaction.id + String(index)}>
                    <TransactionRow {...transaction} />
                  </div>
                );
              })}

              {/* Status Messages Inside Scroll Area */}
              {loading && (
                <div className="text-center py-4 text-gray-500">Loading more transactions...</div>
              )}
              {error && <div className="text-center py-4 text-red-500">{error}</div>}
              {!hasMore && !loading && (
                <div className="text-center py-4 text-gray-500">
                  You've reached the end of the history.
                </div>
              )}
            </>
          ) : (
            <div className="text-center py-8 text-gray-500">No transactions found.</div>
          )}
        </div>
      </div>
    </div>
  );
};
