//DoctorAgendamentoEditPage.jsx
//Nesta página falta: mudar nomes,

import { useState, useEffect } from 'react'
import { useAuth } from '../../_assets/utils/AuthProvider'
import { UserInfos } from '../../_assets/utils/Functions-Endpoints/General'
import API_KEY from '../../_assets/utils/apiKeys'

import FormNovaConsulta from '../../components/agendamento/FormNovaConsulta'


const DoctorAgendamentoEditPage = ({DictInfo, setDictInfo}) => {

  const {getAuthorizationHeader} = useAuth();

  const [idUsuario, setIdUsuario] = useState("")


  const authHeader = getAuthorizationHeader()


  useEffect(() => {
    //console.log(DictInfo.scheduled_at.split("T")[0])
    setDictInfo({...DictInfo, dataAtendimento:DictInfo?.scheduled_at?.split("T")[0]})

    const fetchUserInfo = async () => {
      const InfosUser = await UserInfos(authHeader)
      console.log("Informações", InfosUser)
      setIdUsuario(InfosUser.id)
    }

    fetchUserInfo()



  }, [])

  const handleSave = (DictParaPatch) => {
    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");
    myHeaders.append('apikey', API_KEY)
    myHeaders.append("authorization", authHeader)

    console.log(DictParaPatch)

    var raw = JSON.stringify({"patient_id": DictParaPatch.patient_id,
    "doctor_id": DictParaPatch.doctor_id,
    
    "duration_minutes": 30,

    "chief_complaint": "Dor de cabeça há 3 ",
    
    "created_by": idUsuario,

    "scheduled_at": `${DictParaPatch.dataAtendimento}T${DictParaPatch.horarioInicio}:00.000Z`,
    
    "appointment_type": DictParaPatch.tipo_consulta,
    
    "patient_notes": "Prefiro horário pela manhã",
    "insurance_provider": DictParaPatch.convenio,
    "status": DictParaPatch.status,
    "created_by": idUsuario


    });

   // console.log(DictParaPatch)
    //console.log(id)

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

    fetch(`https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments?id=eq.${DictInfo.id}`, requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));
    }




  return (
    <div>
        <FormNovaConsulta agendamento={DictInfo} setAgendamento={setDictInfo} onSave={handleSave}/>
    </div>
  )
}

export default DoctorAgendamentoEditPage