class AppointmentForm {
    constructor(vehicle) {
      this.vehicle = vehicle;
      this.inputs = [
        'name',
        'email',
        'phone',
        'preferred-contact',
        'message',
        'agreeToOffersCheckbox',
        'privacyPolicyCheckbox',
      ];
      this.initForm();
      this.modalDiv = null;
      this.name = 'appointmentForm';
    }
  
    initForm() {
      this.modalDiv = document.createElement('div');
      const inputIds = [
        {
          id: 'agreeToOffersCheckbox',
          name: 'agreeToOffersCheckbox',
          text: 'I agree to receive periodical offers, newsletter, safety and recall updates from the dealership. Consent can be withdrawn at any time.',
        },
        {
          id: 'privacyPolicyCheckbox',
          name: 'privacyPolicyCheckbox',
          text: 'By submitting this information, you are accepting that it may be collected, used and disclosed as described in our privacy policy.',
        },
      ];
      let checkboxes = ``;
      const vehicleInput = `<input type="hidden" name="vehicle" id="vehicle" value='${JSON.stringify(this.vehicle)}'>`;
      inputIds.forEach((input) => {
        checkboxes += `
              <div class=" mdc-form-field flex flex-row flex-nowrap w-full my-2 lg:my-0 ${input.name} hover:text-red-500">
                  <div class="mdc-checkbox mdc-theme-primary">
                      <input type="checkbox" class="mdc-checkbox__native-control ${input.name}" id="${input.id}" />
                      <div class="mdc-checkbox__background rounded-md">
                          <svg class="mdc-checkbox__checkmark" viewBox="0 0 24 24">
                              <path class="mdc-checkbox__checkmark-path" fill="none" d="M1.73,12.91 8.1,19.28 22.79,4.59"/>
                          </svg>
                          <div class="mdc-checkbox__mixedmark"></div>
                      </div>
                      <div class="mdc-checkbox__ripple p-2"></div>
                  </div>
                  <label for="${input.id}" class="text-sm font-medium text-gray-900 dark:text-gray-300 transition duration-400"> ${input.text}</label>
              </div>`;
      });
      this.modalDiv.innerHTML = `
          <form class="p-4 md:p-5" id="appointmentForm">
            <div class="grid gap-4 grid-cols-2">
                <div class="col-span-2">
                    <label for="name" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Name</label>
                    <input type="text" name="name" id="name" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" placeholder="Jane Doe" required>
                    <div id="nameError" class="text-red-500 hidden">Please enter your name.</div>
                </div>
                <div class="col-span-2">
                    <label for="email" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Email</label>
                    <input type="email" name="email" id="email" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" placeholder="jane@gmail.com" required>
                    <div id="emailError" class="text-red-500 hidden">Please enter a valid email address.</div>
                </div>
                <div class="col-span-2 ">
                    <label for="phone" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Phone</label>
                    <input type="tel" name="phone" id="phone" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" placeholder="(123) 456-7890" required>
                    <div id="phoneError" class="text-red-500 hidden">Please enter a valid phone number.</div>
                </div>
                <div class="col-span-2 ">
                    <label for="preferred-contact" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Preferred Contact Method</label>
                    <select id="preferred-contact" name="preferred-contact" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-500 focus:border-primary-500 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500">
                        <option selected disabled>---</option>
                        <option value="Call">Call</option>
                        <option value="Email" selected>Email</option>
                        <option value="Text">Text</option>
                    </select>
                    <div id="preferredContactError" class="text-red-500 hidden">Please select a preferred contact method.</div>
                </div>
                <div class="col-span-2">
                    <label for="message" name="message" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Product Description</label>
                    <textarea id="message" rows="4" class="block p-2.5 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="I am interested in..."></textarea>
                </div>
            </div>
            ${vehicleInput}
            ${checkboxes}
            <button class="w-full bg-gray-500 hover:bg-gray-800 text-white p-2 rounded-md transition duration-300 finance-view-only" id="send-button">Send</button>
          </form>
              `;
  
      this.checkboxes = this.modalDiv.querySelectorAll('.mdc-checkbox');
      if (this.checkboxes) {
        this.checkboxes.forEach((checkbox, index) => {
          // Initialize the MDCCheckbox with the actual checkbox element
          const checkboxElement = checkbox.querySelector(
            `.mdc-checkbox__native-control.${inputIds[index].name}`
          );
          const checkboxInstance = new mdc.checkbox.MDCCheckbox(checkbox);
  
          // If the checkbox is found, initialize the form field as well
          if (checkboxElement) {
            const formFieldInstance = new mdc.formField.MDCFormField(
              this.modalDiv.querySelector(
                `.mdc-form-field.${inputIds[index].name}`
              )
            );
            formFieldInstance.input = checkboxElement;
          } else {
            console.error('Checkbox element not found:', inputIds[index].id);
          }
        });
      } else {
        console.error('Checkboxes not found');
      }
  
      this.initializeCheckboxes(this.modalDiv, inputIds);
  
      this.initializeFormEventListeners(this.modalDiv);
  
      return this.modalDiv;
    }

    initializeFormEventListeners(modalDiv) {
      let self = this;
      self.inputs.forEach(id => {
          const inputElement = modalDiv.querySelector(`#${id}`);
          if (inputElement) {
              inputElement.addEventListener('input', () => {
                self.saveFormValues(); // Save form values whenever an input changes
              });
          }
      });
  
      const sendButton = modalDiv.querySelector('#send-button');
      
      if (sendButton) {
          sendButton.addEventListener('click', function(e) {
              e.preventDefault();
              if (self.validateForm()) {
                console.log('Form submitted successfully');
              }else{
                return
              }
  
              const formData = {};

              [...['loanTerm', 'intRate', 'downPayment', 'tradeValue', 'paymentFrequency', 'rate', 'customRateValue'],...self.inputs].forEach(inputID => {
                  const inputElement = document.getElementById(inputID);
                  if (inputElement) {
                      formData[inputID] = postDetails.hasOwnProperty(inputID) ? postDetails[inputID] : null;
                  }
              });
              // AJAX request
              jQuery.ajax({
                  type: 'POST',
                  url: ajax_object.ajax_url,
                  data: {
                      action: 'send_appointment_data',
                      appointment_data: formData,
                      nonce: ajax_object.appointment_nonce 
                  },
                  success: function(response) {
                      alert('Appointment data sent successfully!');
                  },
                  error: function(xhr, status, error) {
                      console.error(xhr.responseText);
                  }
              });
          });
      }
  }
  
    initializeFormInputs() {
      const storedValues =
        JSON.parse(localStorage.getItem(`autocart_${this.name}`)) || {};
      for (const key in storedValues) {
        const inputElement = document.getElementById(key);
        if (inputElement) {
          inputElement.value = storedValues[key];
          inputElement.dispatchEvent(new Event('input'));
        }
      }
    }
  
    initializeCheckboxes(modalDiv, inputIds) {
      this.checkboxes = modalDiv.querySelectorAll('.mdc-checkbox');
      if (this.checkboxes) {
        this.checkboxes.forEach((checkbox, index) => {
          const checkboxElement = checkbox.querySelector(
            `.mdc-checkbox__native-control.${inputIds[index].name}`
          );
          const checkboxInstance = new mdc.checkbox.MDCCheckbox(checkbox);
  
          if (checkboxElement) {
            const formFieldInstance = new mdc.formField.MDCFormField(
              modalDiv.querySelector(`.mdc-form-field.${inputIds[index].name}`)
            );
            formFieldInstance.input = checkboxElement;
          } else {
            console.error('Checkbox element not found:', inputIds[index].id);
          }
        });
      } else {
        console.error('Checkboxes not found');
      }
    }
  
    saveFormValues() {
     
      const formValues = {};
  
      this.inputs.forEach((input) => {
        const inputElement = document.getElementById(input);
        if (inputElement) {
          formValues[input] = inputElement.value;
        }
      });
  
      localStorage.setItem(`autocart_${this.name}`, JSON.stringify(formValues));
    }

    validateForm() {
      let isValid = true;
      this.inputs.forEach((id) => {
          const inputElement = document.getElementById(id);
          const errorElement = document.getElementById(`${id}Error`);
  
          if (inputElement && !inputElement.checkValidity()) {
            isValid = false;
            errorElement.classList.remove('hidden');
          } else {
             errorElement.classList.add('hidden'); 
          }
      });
  
      return isValid;
    }
  }
  