import React from 'react'

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

import {useEffect, useState} from 'react'

const EditPage = ( {id, setCurrentPage}) => {

  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));
    
}, [id,requestOptions])

const HandlePutPatient = async () => { 
  

  var myHeaders = new Headers();
  myHeaders.append("Authorization", "Bearer <token>");
  myHeaders.append("Content-Type", "application/json");

  var raw = JSON.stringify(PatientToPUT);

  console.log("Enviando paciente para atualização:", PatientToPUT);

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

  try {
    const response = await fetch(
      "https://mock.apidog.com/m1/1053378-0-default/pacientes/" + PatientToPUT.id, 
      requestOptions
    );

    // se o backend retorna JSON
    const result = await response.json(); 
    console.log("ATUALIZADO COM SUCESSO", result);
    
    return result; 
  } catch (error) {
    console.error("Erro ao atualizar paciente:", error);
    throw error;
  }

  
};

  return (
    <div>

    <PatientForm
    onSave={HandlePutPatient}
    onCancel={() => {setCurrentPage('table')}}
   setCurrentPage={setCurrentPage}
    formData={PatientToPUT}
    setFormData={setPatientPUT}
    />
    
    </div>
  )
}

export default EditPage