"use client";

import { BanknoteArrowUp } from "lucide-react";
import { Typography } from "@/components/atoms/typogrpahy";
import { TransactionDetail } from "../../types/transactionDetail.type";
import { formatBalanceCurrency } from "@/lib/transactionUtil";

const ADMIN_FEE = 10000; // Fixed admin fee

interface WithdrawalDetailCardProps {
  transaction: TransactionDetail;
}

const WithdrawalDetailCard: React.FC<WithdrawalDetailCardProps> = ({
  transaction,
}) => {
  const { withdrawal_detail } = transaction;

  if (!withdrawal_detail) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 shadow-sm border border-gray-100 dark:border-gray-700">
        <Typography variant="h4" className="mb-4">
          Withdrawal Detail Missing
        </Typography>
        <Typography variant="b2">
          withdrawal_detail is null or undefined
        </Typography>
        <pre className="mt-4 text-xs">
          {JSON.stringify(transaction, null, 2)}
        </pre>
      </div>
    );
  }

  // Map channel code to channel name and icon
  const getChannelInfo = (channelCode: string) => {
    const normalizedCode = (channelCode || "").trim().toUpperCase();

    switch (normalizedCode) {
      case "ID_BCA":
      case "BCA":
      case "BCA_VIRTUAL_ACCOUNT":
        return { name: "BCA", icon: "/images/payment-channels/bca.png" };
      case "ID_MANDIRI":
      case "MANDIRI":
      case "MANDIRI_VIRTUAL_ACCOUNT":
        return {
          name: "Mandiri",
          icon: "/images/payment-channels/mandiri.png",
        };
      case "ID_BRI":
      case "BRI":
      case "BRI_VIRTUAL_ACCOUNT":
        return { name: "BRI", icon: "/images/payment-channels/bri.png" };
      case "ID_BNI":
      case "BNI":
      case "BNI_VIRTUAL_ACCOUNT":
        return { name: "BNI", icon: "/images/payment-channels/bni.png" };
      case "ID_OVO":
        return { name: "OVO", icon: "/images/payment-channels/ovo.png" };
      case "ID_DANA":
        return { name: "DANA", icon: "/images/payment-channels/dana.png" };
      case "ID_LINKAJA":
        return {
          name: "LinkAja",
          icon: "/images/payment-channels/linkaja.png",
        };
      case "ID_GOPAY":
        return { name: "GoPay", icon: "/images/payment-channels/gopay.png" };
      case "PAYPAL":
        return { name: "PayPal", icon: "/images/payment-channels/paypal.png" };
      default:
        return {
          name: channelCode?.trim() || "Unknown",
          icon: "/images/payment-channels/bank.png",
        };
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "SUCCESS":
        return {
          text: "Success",
          className: "text-green-600 bg-green-50 border border-green-200 dark:text-green-400 dark:bg-green-900/20 dark:border-green-700",
        };
      case "PENDING":
        return {
          text: "Pending",
          className: "text-yellow-600 bg-yellow-50 border border-yellow-200 dark:text-yellow-400 dark:bg-yellow-900/20 dark:border-yellow-700",
        };
      case "FAILED":
        return {
          text: "Failed",
          className: "text-red-600 bg-red-50 border border-red-200 dark:text-red-400 dark:bg-red-900/20 dark:border-red-700",
        };
      case "REVERSED":
        return {
          text: "Reversed",
          className: "text-orange-600 bg-orange-50 border border-orange-200 dark:text-orange-400 dark:bg-orange-900/20 dark:border-orange-700",
        };
      default:
        return {
          text: status,
          className: "text-gray-600 bg-gray-50 border border-gray-200 dark:text-gray-400 dark:bg-gray-900/20 dark:border-gray-700",
        };
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", {
      day: "2-digit",
      month: "short",
      year: "numeric",
    });
  };

  const formatTime = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleTimeString("en-US", {
      hour: "2-digit",
      minute: "2-digit",
      hour12: false,
    });
  };


  const statusBadge = getStatusBadge(transaction.status);
  const withdrawalChannel =
    withdrawal_detail.channel_code ||
    withdrawal_detail.bank_name ||
    withdrawal_detail.channel_name ||
    "";
  const channelInfo = getChannelInfo(withdrawalChannel);

  // Use withdrawal_detail.amount when available (net amount user receives)
  // Otherwise transaction.amount may be total (withdrawal + admin fee), so subtract admin fee
  const adminFeeValue = typeof withdrawal_detail.admin_fee === "number"
    ? withdrawal_detail.admin_fee
    : ADMIN_FEE;

  let netAmount = typeof withdrawal_detail.amount === "number"
    ? withdrawal_detail.amount
    : Math.max(0, transaction.amount - adminFeeValue);

  // Safety check: if detail amount equals total amount, recalculate to ensure net display
  if (netAmount === transaction.amount) {
    netAmount = Math.max(0, transaction.amount - adminFeeValue);
  }

  const totalAmount = netAmount + adminFeeValue;

  return (
    <div className="space-y-6">
      {/* Header Section - Center Aligned (Card) */}
      <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 shadow-sm border border-gray-100 dark:border-gray-700 text-center">
        <div className="flex justify-center mb-4">
          <BanknoteArrowUp className="w-20 h-16 text-yellow-500" />
        </div>

        {/* Channel Name */}
        <Typography
          variant="h5"
          className="font-bold text-gray-900 dark:text-white mb-3"
        >
          {channelInfo.name}
        </Typography>

        {/* Withdrawal Amount (Net - Amount Received) */}
        <Typography
          variant="h2"
          className="font-bold text-gray-900 dark:text-white mb-2"
        >
          {formatBalanceCurrency(netAmount, transaction.currency)}
        </Typography>

        {/* Subtitle */}
        <Typography
          variant="b2"
          className="text-gray-500 dark:text-gray-400"
        >
          Amount Received
        </Typography>
      </div>

      {/* Middle Section - Transaction Details (Card) */}
      <div className="bg-white dark:bg-gray-800 rounded-2xl p-6 shadow-sm border border-gray-100 dark:border-gray-700">
        <div className="space-y-3">
          <div className="flex justify-between items-center">
            <Typography
              variant="b1"
              className="text-gray-600 dark:text-gray-400"
            >
              Status
            </Typography>
            <span
              className={`px-3 py-1 rounded-full text-xs font-medium ${statusBadge.className}`}
            >
              {statusBadge.text}
            </span>
          </div>

          <div className="flex justify-between items-center">
            <Typography
              variant="b1"
              className="text-gray-600 dark:text-gray-400"
            >
              Payment Channel
            </Typography>
            <Typography
              variant="b1"
              className="font-medium text-gray-900 dark:text-white"
            >
              {channelInfo.name}
            </Typography>
          </div>

          {/* Withdrawal Amount (Total) */}
          <div className="flex justify-between items-center">
            <Typography
              variant="b1"
              className="text-gray-600 dark:text-gray-400"
            >
              Withdrawal Amount
            </Typography>
            <Typography
              variant="b1"
              className="font-medium text-gray-900 dark:text-white"
            >
              {formatBalanceCurrency(totalAmount, transaction.currency)}
            </Typography>
          </div>

          {/* Admin Fee */}
          <div className="flex justify-between items-center">
            <Typography
              variant="b1"
              className="text-gray-600 dark:text-gray-400"
            >
              Admin Fee
            </Typography>
            <Typography
              variant="b1"
              className="font-medium text-gray-900 dark:text-white"
            >
              {formatBalanceCurrency(adminFeeValue, transaction.currency)}
            </Typography>
          </div>

          {/* Amount Received (Net) */}
          <div className="flex justify-between items-center pt-2 border-t border-gray-100 dark:border-gray-700">
            <Typography
              variant="b1"
              className="font-bold text-gray-900 dark:text-white"
            >
              Amount Received
            </Typography>
            <Typography
              variant="b1"
              className="font-bold text-green-600 dark:text-green-400"
            >
              {formatBalanceCurrency(netAmount, transaction.currency)}
            </Typography>
          </div>

          {/* Date */}
          <div className="flex justify-between items-center mt-3">
            <Typography
              variant="b1"
              className="text-gray-600 dark:text-gray-400"
            >
              Date
            </Typography>
            <Typography
              variant="b1"
              className="font-medium text-gray-900 dark:text-white"
            >
              {formatDate(transaction.created_at)}
            </Typography>
          </div>

          {/* Time */}
          <div className="flex justify-between items-center">
            <Typography
              variant="b1"
              className="text-gray-600 dark:text-gray-400"
            >
              Time
            </Typography>
            <Typography
              variant="b1"
              className="font-medium text-gray-900 dark:text-white"
            >
              {formatTime(transaction.created_at)}
            </Typography>
          </div>
        </div>
      </div>
    </div>
  );
};

export default WithdrawalDetailCard;
