import {queryElems, toggleElem} from '../utils/dom.ts';

function initOrgTeamSettings() {
  // on the page "page-content organization new team"
  const pageContent = document.querySelector('.page-content.organization.new.team');
  if (!pageContent) return;
  queryElems(pageContent, 'input[name=permission]', (el) => el.addEventListener('change', () => {
    // Change team access mode
    const val = pageContent.querySelector<HTMLInputElement>('input[name=permission]:checked')?.value;
    toggleElem(pageContent.querySelectorAll('.team-units'), val !== 'admin');
  }));

  const permTable = pageContent.querySelector<HTMLTableElement>('.js-team-units-permissions-table');
  if (!permTable) return;

  const selectAllInputs = Array.from(permTable.querySelectorAll<HTMLInputElement>('.js-team-units-select-all'));
  const categoryRows = Array.from(permTable.tBodies[0]?.rows || []);
  if (!selectAllInputs.length || !categoryRows.length) return;

  const getRowInput = (row: HTMLTableRowElement, value: string) => row.querySelector<HTMLInputElement>(`input[type="radio"][value="${value}"]`);

  const updateSelectAllState = () => {
    let matchedValue: string | null = null;
    for (const input of selectAllInputs) {
      const eligibleInputs = categoryRows
        .map((row) => getRowInput(row, input.value))
        .filter((rowInput) => rowInput && !rowInput.disabled);
      if (!eligibleInputs.length) continue;
      if (eligibleInputs.every((rowInput) => rowInput.checked)) {
        matchedValue = input.value;
        break;
      }
    }
    for (const input of selectAllInputs) {
      input.checked = matchedValue !== null && input.value === matchedValue;
    }
  };

  for (const input of selectAllInputs) {
    input.addEventListener('change', () => {
      if (!input.checked) return;
      for (const row of categoryRows) {
        const rowInput = getRowInput(row, input.value);
        if (rowInput && !rowInput.disabled) rowInput.checked = true;
      }
      updateSelectAllState();
    });
  }

  for (const row of categoryRows) {
    for (const input of row.querySelectorAll<HTMLInputElement>('input[type="radio"]')) {
      input.addEventListener('change', updateSelectAllState);
    }
  }

  updateSelectAllState();
}

export function initOrgTeam() {
  if (!document.querySelector('.page-content.organization')) return;
  initOrgTeamSettings();
}
