import { ManualPaymentMethodAddForm } from '@/manager/modules/ui/payment-method/components/ManualPaymentMethodAddForm';
import { PaymentMethodAddForm } from '@/manager/modules/ui/payment-method/components/PaymentMethodAddForm';
import { PaymentOption, PaymentSelection } from '@/manager/modules/ui/payment-method/payment-method-types';
import { SimpleCheckbox } from '@/manager/shared/components/SimpleCheckbox';
import { RadioButton } from '@/manager/shared/components/RadioButton';
import { getRadioGroupHost } from '@/manager/shared/utils/locator-utils';
import { BaseComponent } from '@/shared/base/BaseComponent';

export class PaymentRadioGroup extends BaseComponent {
  readonly main = getRadioGroupHost(this.host);
  readonly afterFirstInvoicePaymentSection = this.main.getByTestId('after-first-invoice-payment-option');
  readonly afterFirstInvoiceRadioButton = new RadioButton(this.afterFirstInvoicePaymentSection);
  readonly automaticPaymentSection = this.main.getByTestId('automatic-payment-option');
  readonly automaticRadioButton = new RadioButton(this.automaticPaymentSection);
  readonly paymentMethodAddForm = new PaymentMethodAddForm(this.automaticPaymentSection);
  readonly manualPaymentSection = this.main.getByTestId('manual-payment-option');
  readonly manualPaymentRadioButton = new RadioButton(this.manualPaymentSection);
  readonly manualPaymentMethodAddForm = new ManualPaymentMethodAddForm(this.manualPaymentSection);
  readonly chargeUnpaidInvoicesCheckbox = new SimpleCheckbox(this.main.getByTestId('charge-unpaid-invoices-checkbox'));

  async fill(data: PaymentSelection): Promise<void> {
    await this.check(data.option);

    if (data.option === 'charge_automatically' && data.method) {
      await this.paymentMethodAddForm.select(data.method);
    } else if (data.option === 'send_invoice' && data.manual) {
      await this.manualPaymentMethodAddForm.fill(data.manual);
    }

    if (data.chargeUnpaidInvoices != null) {
      await this.chargeUnpaidInvoicesCheckbox.set(data.chargeUnpaidInvoices);
    }
  }

  private check(option: PaymentOption): Promise<void> {
    switch (option) {
      case 'charge_automatically_after_first_invoice':
        return this.afterFirstInvoiceRadioButton.check();
      case 'charge_automatically':
        return this.automaticRadioButton.check();
      case 'send_invoice':
        return this.manualPaymentRadioButton.check();
    }
  }
}
