"use client";

import Image from "next/image";
import { useEffect, useState } from "react";
import { Typography } from "@/components/atoms/typogrpahy";
import { TransactionDetail } from "../../types/transactionDetail.type";
interface TopupDetailCardProps {
  transaction: TransactionDetail;
}

const FALLBACK_PAYMENT_ICON = "/images/payment-channels/creditcard.png";

const getPaymentMethodIcon = (channelName: string) => {
  const formattedName = channelName.toLowerCase().replace(/\s+/g, "");
  return `/images/payment-channels/${formattedName}.png`;
};

interface PaymentMethodIconProps {
  channelName: string;
  width: number;
  height: number;
  className: string;
}

const PaymentMethodIcon: React.FC<PaymentMethodIconProps> = ({
  channelName,
  width,
  height,
  className,
}) => {
  const iconPath = getPaymentMethodIcon(channelName);
  const [src, setSrc] = useState(iconPath);

  useEffect(() => {
    setSrc(iconPath);
  }, [iconPath]);

  return (
    <Image
      src={src}
      alt={channelName}
      width={width}
      height={height}
      className={className}
      unoptimized
      onError={() => {
        if (src !== FALLBACK_PAYMENT_ICON) {
          setSrc(FALLBACK_PAYMENT_ICON);
        }
      }}
    />
  );
};

const TopupDetailCard: React.FC<TopupDetailCardProps> = ({ transaction }) => {
  const { topup_detail } = transaction;

  if (!topup_detail) {
    return null;
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case "SUCCESS":
        return "text-green-600 bg-green-50 border-green-200 dark:text-green-400 dark:bg-green-900/20 dark:border-green-700";
      case "PENDING":
        return "text-yellow-600 bg-yellow-50 border-yellow-200 dark:text-yellow-400 dark:bg-yellow-900/20 dark:border-yellow-700";
      case "FAILED":
        return "text-red-600 bg-red-50 border-red-200 dark:text-red-400 dark:bg-red-900/20 dark:border-red-700";
      case "EXPIRED":
        return "text-gray-600 bg-gray-50 border-gray-200 dark:text-gray-400 dark:bg-gray-900/20 dark:border-gray-700";
      default:
        return "text-gray-600 bg-gray-50 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: true,
    });
  };

  return (
    <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-sm border border-gray-100 dark:border-gray-700 overflow-hidden">
      {/* Header with Channel Icon and Amount - Centered */}
      <div className="text-center py-8 px-6 bg-gray-50 dark:bg-gray-700/50">
        <div className="w-20 h-20 bg-white dark:bg-gray-700 rounded-full flex items-center justify-center mx-auto mb-4 shadow-sm border border-gray-100 dark:border-gray-600">
          <PaymentMethodIcon
            channelName={topup_detail.channel_name}
            width={40}
            height={40}
            className="w-10 h-10 object-contain"
          />
        </div>

        <Typography variant="h2" className="font-bold text-black dark:text-white mb-2">
          Rp{transaction.amount.toLocaleString("id-ID")}
        </Typography>

        <Typography variant="b2" className="text-gray-600 dark:text-gray-400">
          {topup_detail.channel_name}
        </Typography>
      </div>

      {/* Transaction Details Section */}
      <div className="p-6">
        {/* Transaction Details Header */}
        <div className="flex items-center justify-between mb-6">
          <Typography variant="h5" className="font-semibold text-black dark:text-white">
            Transaction Details
          </Typography>
          <button className="p-1">
            <svg
              className="w-5 h-5 text-gray-400"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M5 15l7-7 7 7"
              />
            </svg>
          </button>
        </div>

        <div className="space-y-4">
          {/* Status */}
          <div className="flex justify-between items-center py-3">
            <Typography variant="b2" className="text-gray-600 dark:text-gray-400">
              Status
            </Typography>
            <span
              className={`px-3 py-1 rounded-full text-xs font-medium ${getStatusColor(transaction.status)}`}
            >
              {transaction.status === "SUCCESS"
                ? "Success"
                : transaction.status === "PENDING"
                  ? "Processing"
                  : transaction.status === "FAILED"
                    ? "Failed"
                    : transaction.status}
            </span>
          </div>

          {/* Payment Method */}
          <div className="flex justify-between items-center py-3">
            <Typography variant="b2" className="text-gray-600 dark:text-gray-400">
              Payment Method
            </Typography>
            <div className="flex items-center gap-3">
              <PaymentMethodIcon
                channelName={topup_detail.channel_name}
                width={20}
                height={20}
                className="w-6 h-6 object-contain"
              />
              <Typography variant="b2" className="text-gray-800 dark:text-gray-200">
                {topup_detail.channel_name}
              </Typography>
            </div>
          </div>

          {/* Time and Date - Combined */}
          <div className="flex justify-between items-center py-3">
            <Typography variant="b2" className="text-gray-600 dark:text-gray-400">
              Date & Time
            </Typography>
            <Typography variant="b2" className="text-gray-800 dark:text-gray-200">
              {formatDate(transaction.created_at)}, {formatTime(transaction.created_at)}
            </Typography>
          </div>

          {/* Mobile Number (if available) */}
          {topup_detail.details.mobile_number && (
            <div className="flex justify-between items-center py-3">
              <Typography variant="b2" className="text-gray-600 dark:text-gray-400">
                Mobile Number
              </Typography>
              <Typography variant="b2" className="text-gray-800 dark:text-gray-200">
                {topup_detail.details.mobile_number}
              </Typography>
            </div>
          )}

          {/* Payment Session (if available in details) */}
          {(topup_detail.details as any).payment_session_id && (
            <div className="flex justify-between items-center py-3">
              <Typography variant="b2" className="text-gray-600 dark:text-gray-400">
                Payment Session
              </Typography>
              <Typography variant="b2" className="text-gray-800 dark:text-gray-200">
                Processing
              </Typography>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default TopupDetailCard;
