import React from 'react'
import PatientForm from '../components/patients/PatientForm'
import {useEffect, useState} from 'react'
import { GetPatientByID } from '../components/utils/Functions-Endpoints/Patient'
import API_KEY from '../components/utils/apiKeys'
import {useNavigate, useParams } from 'react-router-dom'
import { useAuth } from '../components/utils/AuthProvider'

const EditPage = ({DictInfo}) => {
  const navigate = useNavigate()
  const [PatientToPUT, setPatientPUT] = useState({})
  const [showSuccessModal, setShowSuccessModal] = useState(false)

   const { getAuthorizationHeader, isAuthenticated } = useAuth();

useEffect(() => {
	setPatientPUT(DictInfo)
}, [DictInfo])

const HandlePutPatient = async () => { 
  const authHeader = getAuthorizationHeader()
  

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

  var raw = JSON.stringify({...PatientToPUT, bmi:Number(PatientToPUT) || null});

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

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

    fetch(`https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/patients?id=eq.${PatientToPUT.id}`,requestOptions) 
      .then(response => {
        console.log(response)
        if (response.ok) {
          setShowSuccessModal(true)
        }
        return response
      })   
      .then(result => console.log(result))
      .catch(error => console.log("erro", error))
   
};

  return (
    <div>

    <PatientForm
    onSave={HandlePutPatient}
    
    formData={PatientToPUT}
    setFormData={setPatientPUT}
    />

    {showSuccessModal && (
      <div
        className="modal fade show delete-modal"
        style={{
          display: "block",
          backgroundColor: "rgba(0, 0, 0, 0,5)",
        }}
        tabIndex="-1"
      >
        <div className="modal-dialog modal-dialog-centered">
          <div className="modal-content">
            <div className="modal-header" style={{ backgroundColor: '#1e3a8a', color: 'white' }}>
              <h5 className="modal-title">
                Paciente Editado
              </h5>
            </div>

            <div className="modal-body">
              <p className="mb-0 fs-5">
                Paciente editado com sucesso!
              </p>
            </div>

            <div className="modal-footer">
              <button
                type="button"
                className="btn btn-primary"
                onClick={() => {
                  setShowSuccessModal(false)
                  navigate(-1)
                }}
              >
                OK
              </button>
            </div>
          </div>
        </div>
      </div>
    )}
    
    </div>
  )
}

export default EditPage
