import React, { useEffect, useState, useCallback } from "react";
import { useParams, useSearchParams } from "react-router-dom";
import { GetDoctorByID } from "../components/utils/Functions-Endpoints/Doctor";
import DoctorForm from "../components/doctors/DoctorForm";
import { useAuth } from "../components/utils/AuthProvider";
import API_KEY from "../components/utils/apiKeys";

const ENDPOINT_AVAILABILITY =
  "https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/doctor_availability";

const DoctorEditPage = ({DictInfo}) => {
  const { getAuthorizationHeader } = useAuth();
  const [DoctorToPUT, setDoctorPUT] = useState({});

  const Parametros = useParams();
  const [searchParams] = useSearchParams();
 
  const DoctorID = "b24c88b2-1d51-4c04-8fe8-e75c3f2817d1";
  const availabilityId = searchParams.get("availabilityId");

  const [availabilityToPATCH, setAvailabilityToPATCH] = useState(null);
  const [mode, setMode] = useState("doctor");
  console.log("teste", DictInfo)

  useEffect(() => {    
   setDoctorPUT(DictInfo)
  }, [DictInfo]);

  const HandlePutDoctor = 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(DoctorToPUT);

    console.log("Enviando médico para atualização (PUT):", DoctorToPUT);

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

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

  // 2. Função para Atualizar DISPONIBILIDADE (PATCH)
  const HandlePatchAvailability = async (data) => {
    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(data);

    console.log("Enviando disponibilidade para atualização (PATCH):", data);

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

    try {
      const response = await fetch(
        `${ENDPOINT_AVAILABILITY}?id=eq.${availabilityId}`,
        requestOptions
      );
      console.log("Resposta PATCH Disponibilidade:", response);
      alert("Disponibilidade atualizada com sucesso!");
      // Opcional: Redirecionar de volta para a lista de disponibilidades
      // navigate('/disponibilidades');
    } catch (error) {
      console.error("Erro ao atualizar disponibilidade:", error);
      alert("Erro ao atualizar disponibilidade.");
      throw error;
    }
  };

  return (
    <div>
      <DoctorForm
        onSave={
          mode === "availability" ? HandlePatchAvailability : HandlePutDoctor
        }
        formData={mode === "availability" ? availabilityToPATCH : DoctorToPUT}
        setFormData={
          mode === "availability" ? setAvailabilityToPATCH : setDoctorPUT
        }
        isEditingAvailability={mode === "availability"}
      />
    </div>
  );
};

export default DoctorEditPage;
