"use client";

import { forwardRef } from "react";
import {
  CreditCardIcon,
  BanknotesIcon,
  CheckCircleIcon,
  EllipsisVerticalIcon,
  ArrowPathIcon,
} from "@heroicons/react/24/outline";
import { Badge } from "@/components/atoms/badge";
import type { PaymentMethod } from "@customer-portal/domain/payments";
import { cn } from "@/lib/utils";

interface PaymentMethodCardProps extends React.HTMLAttributes<HTMLDivElement> {
  paymentMethod: PaymentMethod;
  showActions?: boolean;
  compact?: boolean;
}

const getPaymentMethodIcon = (type: PaymentMethod["type"]) => {
  switch (type) {
    case "CreditCard":
    case "RemoteCreditCard":
      return <CreditCardIcon className="h-5 w-5" />;
    case "BankAccount":
      return <BanknotesIcon className="h-5 w-5" />;
    case "RemoteBankAccount":
      return <ArrowPathIcon className="h-5 w-5" />;
    case "Manual":
    default:
      return <CreditCardIcon className="h-5 w-5" />;
  }
};

const getCardBrandColor = (cardBrand?: string) => {
  switch (cardBrand?.toLowerCase()) {
    case "visa":
      return "text-blue-600";
    case "mastercard":
      return "text-red-600";
    case "amex":
    case "american express":
      return "text-green-600";
    case "discover":
      return "text-orange-600";
    default:
      return "text-gray-600";
  }
};

const PaymentMethodCard = forwardRef<HTMLDivElement, PaymentMethodCardProps>(
  ({ paymentMethod, showActions = true, compact = false, className, ...props }, ref) => {
    const {
      type,
      description,
      gatewayName,
      isDefault,
      expiryDate,
      bankName,
      cardType,
      cardLastFour,
    } = paymentMethod;

    const formatExpiryDate = (expiry?: string) => {
      if (!expiry) return null;
      // Handle different expiry formats (MM/YY, MM/YYYY, MMYY, etc.)
      const cleaned = expiry.replace(/\D/g, "");
      if (cleaned.length >= 4) {
        const month = cleaned.substring(0, 2);
        const year = cleaned.substring(2, 4);
        return `${month}/${year}`;
      }
      return expiry;
    };

    const renderPaymentMethodDetails = () => {
      if (type === "BankAccount" || type === "RemoteBankAccount") {
        return (
          <div className="space-y-1">
            <div className="font-medium text-gray-900">{bankName || "Bank Account"}</div>
            <div className="text-sm text-gray-600">
              {cardLastFour && <span> •••• {cardLastFour}</span>}
            </div>
          </div>
        );
      }

      // Credit Card
      return (
        <div className="space-y-1">
          <div className="font-medium text-gray-900">
            {cardType || "Credit Card"}
            {cardLastFour && <span className="ml-2">•••• {cardLastFour}</span>}
          </div>
          <div className="text-sm text-gray-600">
            {formatExpiryDate(expiryDate) && <span>Expires {formatExpiryDate(expiryDate)}</span>}
            {gatewayName && <span className="ml-2">• {gatewayName}</span>}
          </div>
        </div>
      );
    };

    return (
      <div
        ref={ref}
        className={cn(
          "bg-white border border-gray-200 rounded-lg transition-all duration-200",
          "hover:border-gray-300 hover:shadow-sm",
          isDefault && "ring-2 ring-blue-500 border-blue-200",
          compact ? "p-3" : "p-4",
          className
        )}
        {...props}
      >
        <div className="flex items-start justify-between">
          <div className="flex items-start space-x-3 flex-1 min-w-0">
            {/* Icon */}
            <div
              className={cn(
                "flex-shrink-0 rounded-lg flex items-center justify-center",
                compact ? "w-8 h-8 bg-gray-100" : "w-10 h-10 bg-gray-100",
                type === "CreditCard" || type === "RemoteCreditCard"
                  ? getCardBrandColor(cardType)
                  : "text-gray-600"
              )}
            >
              {getPaymentMethodIcon(type)}
            </div>

            {/* Details */}
            <div className="flex-1 min-w-0">
              {renderPaymentMethodDetails()}

              {/* Description if different from generated details */}
              {description && !description.includes(cardLastFour || "") && (
                <div className="text-sm text-gray-500 mt-1 truncate">{description}</div>
              )}

              {/* Default badge */}
              {isDefault && (
                <div className="mt-2">
                  <Badge variant="success" size="sm" icon={<CheckCircleIcon className="h-3 w-3" />}>
                    Default (Active)
                  </Badge>
                </div>
              )}
            </div>
          </div>

          {/* Actions */}
          {showActions && (
            <div className="flex-shrink-0 ml-2">
              <button
                type="button"
                className="p-1 text-gray-400 hover:text-gray-600 rounded-md hover:bg-gray-100"
                onClick={e => {
                  e.stopPropagation();
                  // Payment method actions (edit, delete) are handled via dedicated modal flows
                  // Future enhancement: Add dropdown menu for quick actions
                }}
              >
                <EllipsisVerticalIcon className="h-5 w-5" />
              </button>
            </div>
          )}
        </div>

        {/* Gateway info for compact view */}
        {compact && gatewayName && (
          <div className="mt-2 text-xs text-gray-500">via {gatewayName}</div>
        )}
      </div>
    );
  }
);

PaymentMethodCard.displayName = "PaymentMethodCard";

export { PaymentMethodCard };
export type { PaymentMethodCardProps };
