import {useState} from 'react';
import PatientForm from '../components/patients/PatientForm';
import API_KEY from '../components/utils/apiKeys';
import { useAuth } from '../components/utils/AuthProvider';
function PatientCadastroManager( {setCurrentPage} ) {

  const { getAuthorizationHeader, isAuthenticated } = useAuth();
  const [formData, setFormData] = useState({})
 
  // Função que será chamada para "salvar" o paciente
  const handleSavePatient = async (patientData) => {
    const authHeader = getAuthorizationHeader();


    var myHeaders = new Headers();
      myHeaders.append("Content-Type", "application/json");
      myHeaders.append("apikey", API_KEY)
      myHeaders.append("Authorization", authHeader)


    console.log('Salvando paciente:', patientData);

    var raw = JSON.stringify(patientData);
    console.log(patientData, 'aqui')

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

    try {
      const response = await fetch("https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/patients", requestOptions);
      const result = await response.json();   
      console.log("Paciente salvo no backend:", result);
      
      return result;
    } catch (error) {
      console.error("Erro ao salvar paciente:", error);
      throw error; 
    }
};


  return (
    <>
      <div className="page-heading">
        <h3>Cadastro de Pacientes</h3>
      </div>
      <div className="page-content">
        <section className="row">
          <div className="col-12">
            {/* Aqui está a lógica principal: */}
            {/* Se a view for 'list', mostramos a lista com o botão. */}
            {/* Se for 'form', mostramos o formulário de cadastro. */}

              <PatientForm
                onSave={handleSavePatient}
                onCancel={() => {setCurrentPage('table')}}
                formData={formData}
                setFormData={setFormData}
              />
            
          </div>
        </section>
      </div>
    </>
  );
}

export default PatientCadastroManager;