import React from 'react'

import PatientForm from '../components/patients/PatientForm'

import {useEffect, useState} from 'react'

const EditPage = ( {id}) => {

  const [PatientToPUT, setPatientPUT] = useState({})

  var requestOptions = {
   method: 'GET',
   redirect: 'follow'
};

useEffect(() => {


fetch(`https://mock.apidog.com/m1/1053378-0-default/pacientes/${id}`, requestOptions)
  .then(response => response.json())
  .then(result => result.data)
  .then(data => setPatientPUT(data))
  .catch(error => console.log('error', error));
    
}, [])

const HandlePutPatient = () => { 
  alert(`Atualizando paciente "${PatientToPUT.nome}" com sucesso`)
    var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer <token>");
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify(PatientToPUT)

console.log(PatientToPUT)

var requestOptions = {
   method: 'PUT',
   headers: myHeaders,
   body: raw,
   redirect: 'follow'
};

fetch("https://mock.apidog.com/m1/1053378-0-default/pacientes/", requestOptions)
   .then(response => response.text())
   .then(result => console.log('ATUALIZADO COM SUCESSO',result))
   .catch(error => console.log('error', error));

  }


  return (

    <div>
    
    <button>Voltar para lista sem salvar</button>

    

    <PatientForm
    onSave={HandlePutPatient}
    onCancel={console.log('Não atualizar')}
   
    formData={PatientToPUT}
    setFormData={setPatientPUT}
    />
    
    </div>
  )
}

export default EditPage