import { Controller } from '@hotwired/stimulus';
import { BUY_FORM_COLLECT_DATA } from '@assets/components/constants/eventTypes';
import { getBuyFormComponent } from '@assets/components/utils';
import { BuyFormCollectDataEvent } from '@assets/components/interfaces';

export default class extends Controller<HTMLDivElement> {
   static targets = [ "checkbox" ];
   declare checkboxTarget: HTMLInputElement;

   static values = {
      componentKey: String,
      chargeId: Number,
      previewMode: Boolean
   };
   declare componentKeyValue: string;
   declare chargeIdValue: number;
   declare previewModeValue: boolean;

   private buyForm: Controller;

   collectDataListener = (event: BuyFormCollectDataEvent) => {
      if (event.isPreviewMode() && !this.previewModeValue) {
         return;
      }

      event.addNote({
         charges: {
            [this.chargeIdValue]: (this.checkboxTarget.checked ? 'Y' : 'N')
         }
      });
   };

   connect() {
      this.buyForm = getBuyFormComponent(this.application, this.componentKeyValue, this.element);
      if (this.buyForm) {
         this.buyForm.element.addEventListener(BUY_FORM_COLLECT_DATA, this.collectDataListener as EventListener);
      }
   }

   disconnect() {
      if (this.buyForm) {
         this.buyForm.element.removeEventListener(BUY_FORM_COLLECT_DATA, this.collectDataListener as EventListener);
      }
   }
}
