import { useModal } from 'components/layers';

import { Button } from 'components/common';
import { AddCardModal, HandleIntentSuccess } from './modals/AddCardModal';
import { PaymentMethod } from './PaymentMethod';

type PaymentMethodCard = {
  id: string;
  brand: string;
  last4: string;
  expYear: string;
  expMonth: string;
  created: string;
  country: string;
};

export interface CheckoutPaymentMethodProps {
  method?: PaymentMethodCard | null;
  billingDetails?: Record<string, string>;
  onChange?: HandleIntentSuccess;
  disabled?: boolean;
  error?: string;
}

export const CheckoutPaymentMethod = ({
  method,
  billingDetails,
  onChange,
  disabled,
  error,
}: CheckoutPaymentMethodProps) => {
  const addCardModal = useModal(AddCardModal, {
    defaultProps: {
      billingDetails: { name: billingDetails?.name },
      onSuccess: onChange,
    },
  });

  return (
    <div className="spacingY4">
      <div className="flex alignCenter justifyBetween">
        <div className="bold">Payment method</div>
        <div>
          <Button
            onClick={() => addCardModal.show()}
            color={!method || error ? 'blue' : 'gray'}
            disabled={disabled}
          >
            {!method ? 'Add payment method' : 'Change payment method'}
          </Button>
        </div>
      </div>
      {method && (
        <PaymentMethod
          brand={method.brand}
          last4={method.last4}
          expYear={method.expYear}
          expMonth={method.expMonth}
          error={Boolean(error)}
        />
      )}
      {error && <div className="fz14 c-red">{error}</div>}
    </div>
  );
};
