import React from 'react'
import { useAuth } from '../components/utils/AuthProvider'
import { useState, useEffect } from 'react'
import API_KEY from '../components/utils/apiKeys'
import { UserInfos } from '../components/utils/Functions-Endpoints/General'
import FormConsultaPaciente from './FormConsultaPaciente'
import { GetDoctorByID } from '../components/utils/Functions-Endpoints/Doctor'
import { GetPatientByID } from '../components/utils/Functions-Endpoints/Patient'
// 1. Importe o useNavigate
import { useNavigate } from 'react-router-dom'

const ConsultaEditPage = ({ DictInfo }) => {
    // 2. Crie a instância do navigate
    const navigate = useNavigate();

    const { getAuthorizationHeader } = useAuth()
    const authHeader = getAuthorizationHeader();

    const [idUsuario, setIDusuario] = useState(null);
    const [Dict, setDict] = useState({});
    const [Medico, setMedico] = useState(null);
    const [Paciente, setPaciente] = useState(null);

    console.log("dentro do edit", DictInfo)


    useEffect(() => {
        setDict({ ...DictInfo });

        const fetchInitialData = async () => {
            if (DictInfo.doctor_id) {
                const medicoData = await GetDoctorByID(DictInfo.doctor_id, authHeader);
                setMedico(medicoData[0]);
            }
            if (DictInfo.patient_id) {
                const pacienteData = await GetPatientByID(DictInfo.patient_id, authHeader);
                setPaciente(pacienteData[0]);
            }
        };

        const fetchUserInfo = async () => {
            const result = await UserInfos(authHeader);
            setIDusuario(result?.profile?.id);
        };

        fetchUserInfo();
        fetchInitialData();

    }, [DictInfo, authHeader]);

    useEffect(() => {
        if (Medico) {
            setDict(prevDict => ({
                ...prevDict,
                medico_nome: Medico?.full_name,
                dataAtendimento: DictInfo.scheduled_at?.split("T")[0]
            }));
        }
    }, [Medico, DictInfo.scheduled_at]);

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

            const 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,
            });

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

            const response = await fetch(`https://yuanqfswhberkoevtmfr.supabase.co/rest/v1/appointments?id=eq.${DictInfo.id}`, requestOptions);

            if (!response.ok) {
                const text = await response.text();
                console.error('Erro no PATCH:', response.status, text);
                throw new Error('Erro na API');
            }

            const updatedData = await response.json();
            if (updatedData && updatedData.length > 0) {
                setDict(updatedData[0]);
            }

            console.log('Consulta atualizada com sucesso!', updatedData);
            alert('Consulta atualizada com sucesso!');

        } catch (error) {
            console.error('Erro ao salvar consulta:', error);
            alert('Erro ao salvar consulta. Veja o console.');
        }
    };
    const handleCancel = () => {
        navigate(-1); 
    };

    return (
        <div>
            {}
            <FormConsultaPaciente
                agendamento={Dict}
                setAgendamento={setDict}
                onSave={handleSave}
                onCancel={handleCancel}
            />
        </div>
    )
}

export default ConsultaEditPage;
