"use client";

import { formatBalanceCurrency } from "@/lib/transactionUtil";
import { Transaction } from "@/modules/walletModule/types/transaction.type";
import Link from "next/link";
import { TransactionIcon } from "./transactionIcon";
import { getTransactionStatusDisplay } from "./transactionStatus";
import { Repeat } from "lucide-react";

const ADMIN_FEE = 10000; // Fixed admin fee

export const TransactionRow: React.FC<Transaction> = ({
  id,
  amount,
  currency,
  created_at,
  updated_at,
  transaction_type,
  status,
  withdrawal_detail,
}) => {
  const transactionDate = created_at ?? updated_at;
  const parsedTransactionDate = transactionDate ? new Date(transactionDate) : null;
  const formattedDate =
    parsedTransactionDate && !Number.isNaN(parsedTransactionDate.getTime())
      ? parsedTransactionDate.toLocaleDateString("en-US", {
          month: "short",
          day: "numeric",
          year: "numeric",
        })
      : "Date unavailable";
  const isTopup = transaction_type === "TOPUP";
  const isWithdrawal = transaction_type === "WITHDRAWAL";
  const statusDisplay = getTransactionStatusDisplay(status);

  // For withdrawals, we want to display the NET amount (what user receives), not the total deducted
  const adminFeeValue =
    typeof withdrawal_detail?.admin_fee === "number" ? withdrawal_detail.admin_fee : ADMIN_FEE;

  // Calculate net amount:
  // 1. Try withdrawal_detail.amount
  // 2. If missing, use transaction.amount - adminFee
  // 3. Safety: If withdrawal_detail.amount equals transaction.amount (total), force recalculation to be net
  let withdrawalAmount =
    typeof withdrawal_detail?.amount === "number"
      ? withdrawal_detail.amount
      : Math.max(0, amount - adminFeeValue);

  if (isWithdrawal && withdrawalAmount === amount) {
    withdrawalAmount = Math.max(0, amount - adminFeeValue);
  }

  // Final check to handle fallback
  withdrawalAmount = isWithdrawal ? withdrawalAmount : amount;

  const adminFeeDisplay = adminFeeValue;

  // Log amount for CHARGE before Math.ceil (for debugging)
  const displayAmount = isWithdrawal ? withdrawalAmount : amount;
  if (transaction_type === "CHARGE") {
    console.log("[TransactionRow] CHARGE amount before Math.ceil:", {
      amount: displayAmount,
      afterCeil: Math.ceil(displayAmount),
      transactionId: id,
    });
  }

  return (
    <Link
      href={`/transactions/${id}`}
      className="flex items-center justify-between p-3 sm:p-4 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors duration-200"
    >
      <div className="flex items-center space-x-3 sm:space-x-4">
        <div
          className={`p-2 sm:p-3 rounded-full ${isTopup ? "bg-green-100" : isWithdrawal ? "bg-yellow-100" : "bg-red-100"}`}
        >
          <TransactionIcon type={transaction_type} className="w-5 h-5 sm:w-6 sm:h-6" />
        </div>

        <div>
          <p className="font-semibold text-gray-800 dark:text-gray-100 text-xs sm:text-sm">
            {transaction_type}
          </p>
          <p className="text-xs sm:text-sm text-gray-500 dark:text-gray-400">{formattedDate}</p>
          <span
            className={`mt-1 inline-flex rounded-full px-2 py-0.5 text-[10px] font-medium sm:text-xs ${statusDisplay.className}`}
          >
            {statusDisplay.label}
          </span>
        </div>
      </div>
      <div
        className={`flex flex-col items-end gap-1 ${isTopup ? "text-green-600" : isWithdrawal ? "text-yellow-600" : "text-red-600"}`}
      >
        <div className="flex items-center gap-1 font-semibold text-xs sm:text-sm">
          {isTopup ? "+" : isWithdrawal ? <Repeat className="w-3 h-3 sm:w-4 sm:h-4" /> : "-"}{" "}
          {formatBalanceCurrency(Math.ceil(displayAmount), currency)}
        </div>
        {isWithdrawal && (
          <p className="text-[10px] sm:text-xs text-gray-500 dark:text-gray-400">
            Admin fee: {formatBalanceCurrency(adminFeeDisplay, currency)}
          </p>
        )}
      </div>
    </Link>
  );
};
