import {registerGlobalInitFunc} from '../modules/observer.ts';
import {toggleElem, toggleElemClass} from '../utils/dom.ts';

export function initActionsPermissionsForm(): void {
  registerGlobalInitFunc('initRepoActionsPermissionsForm', initRepoActionsPermissionsForm);
  registerGlobalInitFunc('initOwnerActionsPermissionsForm', initOwnerActionsPermissionsForm);
}

function initRepoActionsPermissionsForm(form: HTMLFormElement) {
  initActionsOverrideOwnerConfig(form);
  initActionsPermissionTable(form);
}

function initOwnerActionsPermissionsForm(form: HTMLFormElement) {
  initActionsPermissionTable(form);
}

function initActionsPermissionTable(form: HTMLFormElement) {
  // show or hide permissions table based on enable max permissions checkbox (aka: whether you use custom permissions or not)
  const permTable = form.querySelector<HTMLTableElement>('.js-permissions-table')!;
  const enableMaxCheckbox = form.querySelector<HTMLInputElement>('input[name=enable_max_permissions]')!;
  const onEnableMaxCheckboxChange = () => toggleElem(permTable, enableMaxCheckbox.checked);
  onEnableMaxCheckboxChange();
  enableMaxCheckbox.addEventListener('change', onEnableMaxCheckboxChange);

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

  const updateSelectAllState = () => {
    let matchedValue: string | null = null;
    for (const input of selectAllInputs) {
      const everyRowMatches = categoryRows.every((row) => row.querySelector<HTMLInputElement>(`input[type="radio"][value="${input.value}"]`)?.checked === true);
      if (everyRowMatches) {
        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) {
        row.querySelector<HTMLInputElement>(`input[type="radio"][value="${input.value}"]`)!.checked = true;
      }
      updateSelectAllState();
    });
  }

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

  updateSelectAllState();
}

function initActionsOverrideOwnerConfig(form: HTMLFormElement) {
  // enable or disable repo token permissions config section based on override owner config checkbox
  const overrideOwnerConfig = form.querySelector<HTMLInputElement>('input[name=override_owner_config]')!;
  const repoTokenPermConfigSection = form.querySelector('.js-repo-token-permissions-config')!;
  const onOverrideOwnerConfigChange = () => toggleElemClass(repoTokenPermConfigSection, 'container-disabled', !overrideOwnerConfig.checked);
  onOverrideOwnerConfigChange();
  overrideOwnerConfig.addEventListener('change', onOverrideOwnerConfigChange);
}
