const teams = [
  'Lincoln County Chargers',
  'Carolina Bears',
  'Chapel Grove Wildcats',
  'Cleveland County Seminoles',
  'Cramerton Panthers',
  'Dallas Wildcats',
  'East Lincoln Mustangs',
  'Gyso Jr. Huskies',
  'Kings Mountain Elite',
  'Mountain View Tigers',
  'Next Level Spartans',
  'Port City Gators',
  'Southern Masterminds',
  'West Carolina Ducks',
];

const pfTemplates = {
  football: [
    { name: 'full_name', label: 'Full Name', type: 'text' },
    { name: 'dob', label: 'Birth Date', type: 'date' },
    // { name: 'weight', label: 'Weight', type: 'text' },
    { name: 'team_name', label: 'Team Name', type: 'select', options: teams },
    { name: 'age_group', label: 'Age Group', type: 'select', options: ['TM 5-6', 'MM 7-8', 'JV 9-10', 'V 11-12'] },
    // { name: 'jersey', label: 'Jersey Number', type: 'text' },
    { name: 'school_name', label: 'School Name', type: 'text' },
  ],
  cheer: [
    { name: 'full_name', label: 'Full Name', type: 'text' },
    { name: 'dob', label: 'Birth Date', type: 'date' },
    { name: 'team_name', label: 'Team Name', type: 'select', options: teams },
    { name: 'age_group', label: 'Age Group', type: 'select', options: ['TM 5-6', 'MM 7-8', 'JV 9-10', 'V 11-12'] },
    { name: 'school_name', label: 'School Name', type: 'text' },
  ],
  admin: [
    { name: 'admin_name', label: "Administrator's Name", type: 'text' },
    { name: 'organization', label: 'Organization/Title', type: 'text' },
  ],
  coach: [
    { name: 'full_name', label: "Coach's Name", type: 'text' },
    { name: 'sport', label: 'Sport', type: 'select', options: ['Football', 'Cheerleading'] },
    { name: 'team_name', label: 'Team Name', type: 'select', options: teams },
    { name: 'age_group', label: 'Age Group', type: 'select', options: ['TM 5-6', 'MM 7-8', 'JV 9-10', 'V 11-12'] },
  ],
  mom: [
    { name: 'full_name', label: "Team Mom's Name", type: 'text' },
    { name: 'sport', label: 'Sport', type: 'select', options: ['Football', 'Cheerleading'] },
    { name: 'team_name', label: 'Team Name', type: 'select', options: teams },
    { name: 'age_group', label: 'Age Group', type: 'select', options: ['TM 5-6', 'MM 7-8', 'JV 9-10', 'V 11-12'] },
  ],
};

document.addEventListener('DOMContentLoaded', () => {
  const form = document.getElementById('pf-form');
  const templateSelect = document.getElementById('pf-template');
  const fieldsContainer = document.getElementById('pf-fields');

  function validateFieldsAndShowMessages() {
    const requiredFields = fieldsContainer.querySelectorAll('input, select');
    let allFilled = true;

    requiredFields.forEach((field) => {
      const wrapper = field.closest('.pf-form-element');
      if (!field.value.trim()) {
        allFilled = false;
        wrapper.classList.add('invalid');
      }
    });

    return allFilled;
  }

  function checkFormValidity() {
    const requiredFields = fieldsContainer.querySelectorAll('input, select');
    const allFilled = Array.from(requiredFields).every((field) => {
      return field.value.trim() !== '';
    });
  }

  templateSelect.addEventListener('change', () => {
    const selected = templateSelect.value;
    fieldsContainer.innerHTML = '';

    if (pfTemplates[selected]) {
      pfTemplates[selected].forEach((field) => {
        const wrapper = document.createElement('div');
        wrapper.className = 'pf-form-element';

        const label = document.createElement('label');
        label.htmlFor = field.name;
        label.textContent = field.label;

        let input;
        if (field.type === 'select') {
          input = document.createElement('select');
          input.name = field.name;
          input.id = field.name;

          field.options.forEach((opt) => {
            const option = document.createElement('option');
            option.value = opt;
            option.textContent = opt;
            input.appendChild(option);
          });
        } else {
          input = document.createElement('input');
          input.type = field.type;
          input.name = field.name;
          input.id = field.name;
        }

        input.addEventListener('input', () => {
          const wrapper = input.closest('.pf-form-element');
          wrapper.classList.remove('invalid');
          checkFormValidity();
        });

        // Add error message div
        const error = document.createElement('div');
        error.className = 'pf-error-message';
        error.textContent = 'This field is required.';

        wrapper.appendChild(label);
        wrapper.appendChild(input);
        wrapper.appendChild(error);
        fieldsContainer.appendChild(wrapper);
      });
    }
    checkFormValidity();
  });

  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    // Clear previous error states first
    fieldsContainer.querySelectorAll('.pf-form-element').forEach((wrapper) => {
      wrapper.classList.remove('invalid');
    });

    if (!validateFieldsAndShowMessages()) {
      return; // Don't proceed if not valid
    }
    const formData = new FormData(form);
    const template = formData.get('template');
    const data = {};
    formData.forEach((value, key) => {
      data[key] = value;
    });

    if (template === 'football') {
      data['weight'] = '';
    }

    const res = await fetch('/wp-admin/admin-ajax.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({
        action: 'pf_get_template',
        template,
        data: JSON.stringify(data),
      }),
    });

    const html = await res.text();
    let printWin;
    try {
      printWin = window.open('about:blank', '_blank', 'width=1200,height=800,menubar=yes,toolbar=yes');
      if (!printWin) {
        alert('Please allow popups for this website to print forms. May need to reclick the print button on the form.');
        return;
      }
    } catch (e) {
      alert('Please allow popups for this website to print forms. May need to reclick the print button on the form.');
      return;
    }

    const interval = setInterval(() => {
      if (printWin.document.readyState === 'complete') {
        clearInterval(interval);

        const doc = printWin.document;
        const head = doc.head;
        const body = doc.body;

        // Set charset to UTF-8
        const charsetMeta = doc.createElement('meta');
        charsetMeta.setAttribute('charset', 'utf-8');
        head.appendChild(charsetMeta);

        // Set the title tag
        const title = doc.createElement('title');
        title.textContent = 'Print Form';
        head.appendChild(title);

        // Add meta tag for Safari
        const meta = doc.createElement('meta');
        meta.name = 'viewport';
        meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0';
        head.appendChild(meta);

        // Add stylesheet
        const link = doc.createElement('link');
        link.rel = 'stylesheet';
        link.href = printableFormsVars.cssUrl;
        link.type = 'text/css';
        head.appendChild(link);

        // Add print-specific styles
        const style = doc.createElement('style');
        style.textContent = `
          @media print {
            @page {
              size: 11in 8.5in landscape;
              margin: 0.5in;
            }
            * {
              box-sizing: border-box;
            }
          }
        `;
        head.appendChild(style);

        // Inject HTML content
        body.innerHTML = html;

        // Wait for styles to apply
        setTimeout(() => {
          printWin.focus();
          printWin.alert('If not already selected please select "Landscape" orientation, and uncheck "Print headers and footers" in the print dialog.');
          printWin.print();
        }, 1000);
      }
    }, 300);
  });
});
