//debugger;
function Form(el, data, okCallback, cancelCallback){

  let inputCreators = {
    String(key, value, oninput){ 
        let input = document.createElement('input');
        input.type = 'text'
        input.placeholder = key.slice(1, key.length);
        input.id = `${key}`;

        if(value.charAt(0) === '*') {
          data[key] = '';
          input.type = 'password';
          input.placeholder = 'password';
          input.id = `${key}`;
          input.oninput     = () => oninput(input.value);
        return input;
        }

        input.value       = value
        input.oninput     = () => oninput(input.value)
        return input
    },
    Boolean(key, value, oninput){
        //label for с input type='checkbox' внутри
        let input = document.createElement('input');
        input.type = 'checkbox'
        input.placeholder = key
        input.checked      = value
        input.id = `${key}`;
        input.oninput     = () => oninput(input.checked)
        return input
    },
    Date: function (key, value, oninput){
        //используйте datetime-local let input = document.createElement('input');
        let input = document.createElement('input')
        input.type = 'datetime-local'
        input.placeholder = key
        input.id = `${key}`;
        input.value       = value.toISOString().slice(0,-1);
        input.oninput     = () => oninput(Date(input.value))
        return input

    },
    //и др. по вкусу, например textarea для длинных строк
  }

  this.validators = {}; 

  let table = document.createElement('table');

  document.body.appendChild(table);  
  
  for (let [key, value] of Object.entries(data)) {
    let tr = document.createElement('tr');
    let th = document.createElement('th'); 
    let td = document.createElement('td');
    let tdForWrong = document.createElement('td');
    const span = document.createElement('span');
    const spanKey = document.createElement('span');
    let input = inputCreators[value.constructor.name](key, value, function enterPlase (value){
      data[key] = value;
    }) 
    
    input.addEventListener('input', () => {
      
      let resultInputValue = input.value;
      let resultValadators = true;

      if (value.constructor.name === Boolean) {
        resultInputValue = input.checked;  
      };
      
      if (typeof this.validators[key] === 'function') {
        resultValadators = this.validators[key](resultInputValue, key, data, input); 
        

        if (typeof resultValadators === 'string') {
          resultValadators = false;
          input.style.backgroundColor = 'red';
          tdForWrong.innerHTML = ` ${this.validators[key](resultInputValue, key, data, input)}`
        }
        if (resultValadators) {
          input.style.backgroundColor = 'white';
          tdForWrong.innerHTML = ` `;
        }
      }
      resultInputValue === '' ? input.style.border = '3px solid red': input.style.border = null; 

      })

    if (key.charAt(0) === '*') {
      const start = key.charAt(0);
      spanKey.innerHTML = `${key.slice(1, key.length)}`;
      span.style.color = 'red';
      span.innerText = `${start} `;
      
    } else {
      spanKey.innerHTML = key;
    }

  
    table.append(tr); 
    tr.append(th);
    tr.append(td);
    th.appendChild(span);
    th.append(spanKey);
    td.appendChild(input);
    tr.append(tdForWrong);

  }

  this.copyData = {...data}; 

  this.checkInput = function () {
      let input = document.querySelector(input);
      input.value
  }

  let formBody = document.createElement('div')
  let okButton = document.createElement('button')
  okButton.innerHTML = 'OK';
    
  okButton.addEventListener('click', () => { 
    let countKey = 0;
    let countvalidators = 0;

    for (let [key, value] of Object.entries(data)) {
      let resultInputValue = value;
      let resultValadators = true;
      let input = document.getElementById(value);

      if (typeof this.validators[key] === 'function') {
        resultValadators = this.validators[key](resultInputValue, key, data, input); 
        
        if (typeof resultValadators === 'string') {
          resultValadators = false;
        }
      }
      
      if (resultValadators && resultInputValue ) {
        countvalidators++;
      }

      countKey++;
    }

    if (countKey === countvalidators) {
      this.okCallback(data);
    }
  })

  let cancelButton = document.createElement('button')
  cancelButton.innerHTML = 'Cancel'

  formBody.innerHTML = '<h1>тут будет форма после перервы</h1>'

  cancelButton.addEventListener('click', () => { console.log(this.copyData)

    for (let [key, value] of Object.entries(this.copyData)) {
      let input = document.getElementById(key);

      if( value.constructor.name === 'String') {
      input.value = `${value}`;
      }

      if (value.constructor.name === 'Boolean') {
        input.checked = `${value}`;
      }

      if (value.constructor.name === 'Date') {
        input.value = value.toISOString().slice(0,-1);
      }
    }
  })
  
  if (typeof okCallback === 'function'){
      formBody.appendChild(okButton);
      okButton.onclick = (e) => {
          //console.log(this)
          this.okCallback(e)
      }
  }

  if (typeof cancelCallback === 'function'){
      formBody.appendChild(cancelButton);
      cancelButton.onclick = cancelCallback
  }

  el.appendChild(formBody);

  
  




  this.okCallback;
  this.cancelCallback = cancelCallback

  this.data           = data
  
}


let form = new Form(document.body, {
  '*name': 'Anaaa',
  surname: 'Skywalker',
  married: true,
  birthday: new Date((new Date).getTime() - 86400000 * 30*365)
}, () => console.log('ok'),() => console.log('cancel') )
form.okCallback = (what) => console.log(what)

form.validators.surname = (value, key, data, input) => value.length > 2 && 
                                                   value[0].toUpperCase() == value[0] &&
                                                  !value.includes(' ') ? true : 'Wrong name'
//console.log(form)

