import React, { useMemo, useState } from 'react';
import { Input, Icon } from '@akinon/next/components';
import { detectCardType, getCardIcon, getCvcLength } from '../utils/card-utils';
import { getCappedRewardTotal } from '../utils/reward-utils';
import type { CardListProps } from '../types/custom-render.types';
import MasterpassSecurityInfo from './masterpass-security-info';

const CardList: React.FC<CardListProps> = ({
  cards,
  onCardSelect,
  selectedCard,
  onRemove,
  removingCardId,
  cvc = '',
  onCvcChange,
  cvcRequired = false,
  availableRewards = [],
  selectedRewards = [],
  isLoadingRewards = false,
  onOpenRewardModal,
  rewardCurrency,
  rewardPayableAmount,
  texts
}) => {
  const [localCvc, setLocalCvc] = useState(cvc);

  const handleCvcChange = (value: string) => {
    const numericValue = value.replace(/\D/g, '').slice(0, 4);
    setLocalCvc(numericValue);
    onCvcChange?.(numericValue);
  };

  const orderedCards = useMemo(() => {
    if (!selectedCard) return cards;
    const idx = cards.findIndex(
      (c) => c.uniqueCardNumber === selectedCard.uniqueCardNumber
    );
    if (idx <= 0) return cards;
    const reordered = [...cards];
    const [picked] = reordered.splice(idx, 1);
    reordered.unshift(picked);
    return reordered;
  }, [cards, selectedCard]);

  return (
    <div className="flex flex-col gap-4">
      {orderedCards.map((card) => {
        const isSelected =
          selectedCard?.uniqueCardNumber === card.uniqueCardNumber;
        const expectedCvcLength = getCvcLength(detectCardType(card.cardBin));

        return (
          <div
            key={card.uniqueCardNumber}
            className={`border transition-all cursor-pointer ${
              isSelected
                ? 'border-[#000000] bg-[#000000]/5'
                : 'border-[#eeeeee] hover:border-[#ebebeb]'
            }`}
            onClick={() => onCardSelect(card)}
          >
            <div className="flex items-center justify-between p-4">
              {/* Selection Indicator - Moved to beginning */}
              <div className="flex items-center space-x-4">
                <div
                  className={`
                    w-4 h-4 border-2 rounded-full flex items-center justify-center
                    ${
                      isSelected
                        ? 'border-[#000000] bg-primary'
                        : 'border-[#ebebeb]'
                    }
                  `}
                >
                  {isSelected && (
                    <div className="w-2 h-2 bg-[#ffffff] rounded-full"></div>
                  )}
                </div>

                <img
                  src={getCardIcon(card.cardBin).src}
                  alt={card.cardType}
                  className="w-8 h-6 object-contain"
                />
                <div>
                  <div className="font-medium text-[#4a4f54]">
                    {card.maskedCardNumber}
                  </div>
                  <div className="text-sm text-[#c9c9c9]">{card.cardAlias}</div>
                  <div className="flex items-center space-x-2 mt-1">
                    <span className="text-xs px-2 py-1 bg-gray-100">
                      {card.cardType}
                    </span>
                    {card.isDefaultCard && (
                      <span className="text-xs px-2 py-1 bg-[#000000]/10 text-[#000000]">
                        {texts.defaultCardText}
                      </span>
                    )}
                    {card.expireSoon && (
                      <span className="text-xs px-2 py-1 bg-[#d08800]/10 text-[#d08800]">
                        {texts.expiresSoonText}
                      </span>
                    )}
                  </div>
                </div>
              </div>

              {onRemove && (
                <button
                  className="p-2 text-[#d7d7d7] hover:text-[#ff6367] transition-colors disabled:opacity-50 bg-[#f5f5f5] rounded-full"
                  disabled={removingCardId === card.uniqueCardNumber}
                  onClick={(e) => {
                    e.stopPropagation();
                    onRemove(card);
                  }}
                >
                  {removingCardId === card.uniqueCardNumber ? (
                    <div className="animate-spin h-5 w-5 border-b-2 border-[#ff6367]"></div>
                  ) : (
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="20"
                      height="20"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      className="text-[#9d9d9d]"
                    >
                      <path d="M3 6h18" />
                      <path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6" />
                      <path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2" />
                    </svg>
                  )}
                </button>
              )}
            </div>

            {isSelected &&
              (isLoadingRewards || availableRewards.length > 0) && (
                <div
                  className="border-t border-[#eeeeee] p-4 bg-[#fafafa] flex items-center justify-between gap-3"
                  onClick={(e) => e.stopPropagation()}
                >
                  <div className="flex items-center gap-2 min-w-0">
                    <Icon name="gift" size={16} className="text-[#000000]" />
                    <div className="min-w-0">
                      <p className="text-sm font-medium text-[#4a4f54] truncate">
                        {texts.rewardOpenButtonText}
                      </p>
                      {selectedRewards.length > 0 ? (
                        <p className="text-xs text-[#00a63d] truncate">
                          {(texts.rewardSelectedSummaryText || '').replace(
                            '{count}',
                            String(selectedRewards.length)
                          )}
                          {' · '}
                          {getCappedRewardTotal(
                            selectedRewards,
                            rewardPayableAmount
                          ).toFixed(2)}{' '}
                          {(rewardCurrency || '').toUpperCase()}
                        </p>
                      ) : (
                        <p className="text-xs text-[#9d9d9d] truncate">
                          {(texts.rewardAvailableSummaryText || '').replace(
                            '{count}',
                            String(availableRewards.length)
                          )}
                        </p>
                      )}
                    </div>
                  </div>
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      onOpenRewardModal?.();
                    }}
                    disabled={isLoadingRewards}
                    className="px-3 py-1.5 text-xs border border-[#000000] text-[#000000] hover:bg-[#000000] hover:text-white transition-colors disabled:opacity-50 shrink-0"
                  >
                    {selectedRewards.length > 0
                      ? texts.rewardModalConfirmText
                      : texts.rewardOpenButtonText}
                  </button>
                </div>
              )}

            {isSelected && cvcRequired && (
              <div
                className="border-t border-[#eeeeee] p-4 bg-[#f7f7f7]"
                onClick={(e) => e.stopPropagation()}
              >
                <div className="flex items-center gap-4">
                  <div className="flex-1">
                    <label
                      htmlFor={`cvc-${card.uniqueCardNumber}`}
                      className="block text-sm font-medium text-[#686868] mb-2"
                    >
                      {texts.cvcCardLabel}
                      <span className="text-[#ff6367]"> *</span>
                    </label>
                    <Input
                      id={`cvc-${card.uniqueCardNumber}`}
                      type="text"
                      placeholder={
                        expectedCvcLength === 4
                          ? texts.cvcPlaceholder4
                          : texts.cvcPlaceholder3
                      }
                      value={localCvc}
                      onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                        handleCvcChange(e.target.value)
                      }
                      maxLength={expectedCvcLength}
                      className="w-32"
                    />
                    <p className="text-xs text-[#c9c9c9] mt-1">
                      {texts.cvcCardHelpText
                        ?.replace('{length}', expectedCvcLength.toString())
                        .replace(
                          '{side}',
                          expectedCvcLength === 4
                            ? texts.cvcFrontText
                            : texts.cvcBackText
                        )}
                    </p>
                  </div>
                  <div className="flex items-center text-sm text-[#9d9d9d]">
                    <Icon
                      name="shield-check"
                      size={16}
                      className="mr-1 text-[#00a63d]"
                    />
                    <span>{texts.secureCardText}</span>
                  </div>
                </div>
              </div>
            )}
          </div>
        );
      })}
      <MasterpassSecurityInfo texts={texts} />
    </div>
  );
};

export default CardList;
