'use client' import { useState, useEffect } from 'react' import { useRouter, useParams } from 'next/navigation' import { useTheme } from 'next-themes' import Image from 'next/image' import { Button } from '@/components/ui/button' import { ArrowLeft, Printer, Download } from 'lucide-react' import { buscarRelatorioPorId, getDoctorById, buscarMedicosPorIds, buscarPacientePorId } from '@/lib/api' import { ENV_CONFIG } from '@/lib/env-config' import ProtectedRoute from '@/components/shared/ProtectedRoute' import { useAuth } from '@/hooks/useAuth' export default function LaudoPage() { const router = useRouter() const params = useParams() const { user } = useAuth() const { theme } = useTheme() const reportId = params.id as string const isDark = theme === 'dark' const [report, setReport] = useState(null) const [doctor, setDoctor] = useState(null) const [patient, setPatient] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState('') useEffect(() => { if (!reportId) return let mounted = true async function loadReport() { try { setLoading(true) const reportData = await buscarRelatorioPorId(reportId) if (!mounted) return setReport(reportData) // Load patient info if patient_id exists const rd = reportData as any const patientId = rd?.patient_id if (patientId) { try { const patientData = await buscarPacientePorId(patientId).catch(() => null) if (mounted && patientData) { setPatient(patientData) } } catch (e) { console.warn('Erro ao carregar dados do paciente:', e) } } // Load doctor info using the same strategy as paciente/page.tsx const maybeId = rd?.doctor_id ?? rd?.created_by ?? rd?.doctor ?? null if (maybeId) { try { // First try: buscarMedicosPorIds let doctors = await buscarMedicosPorIds([maybeId]).catch(() => []) if (!doctors || doctors.length === 0) { // Second try: getDoctorById const doc = await getDoctorById(String(maybeId)).catch(() => null) if (doc) doctors = [doc] } if (!doctors || doctors.length === 0) { // Third try: direct REST with user_id filter const token = (typeof window !== 'undefined') ? (localStorage.getItem('auth_token') || localStorage.getItem('token') || sessionStorage.getItem('auth_token') || sessionStorage.getItem('token')) : null const headers: Record = { apikey: (ENV_CONFIG as any).SUPABASE_ANON_KEY, Accept: 'application/json' } if (token) headers.Authorization = `Bearer ${token}` const url = `${(ENV_CONFIG as any).SUPABASE_URL}/rest/v1/doctors?user_id=eq.${encodeURIComponent(String(maybeId))}&limit=1` const res = await fetch(url, { method: 'GET', headers }) if (res && res.status < 400) { const rows = await res.json().catch(() => []) if (rows && Array.isArray(rows) && rows.length) { doctors = rows } } } if (mounted && doctors && doctors.length > 0) { setDoctor(doctors[0]) } } catch (e) { console.warn('Erro ao carregar dados do profissional:', e) } } } catch (err) { if (mounted) setError('Erro ao carregar o laudo.') console.error(err) } finally { if (mounted) setLoading(false) } } loadReport() return () => { mounted = false } }, [reportId]) const handlePrint = () => { window.print() } const handleDownloadPDF = async () => { if (!report) return try { // Para simplificar, vamos usar jsPDF com html2canvas para capturar o conteúdo const { jsPDF } = await import('jspdf') const html2canvas = await import('html2canvas').then((m) => m.default) // Criar um elemento temporário com o conteúdo const element = document.createElement('div') element.style.position = 'absolute' element.style.left = '-9999px' element.style.width = '210mm' // A4 width element.style.padding = '20mm' element.style.backgroundColor = 'white' element.style.fontFamily = 'Arial, sans-serif' // Extrair informações const reportDate = new Date(report.report_date || report.created_at || Date.now()).toLocaleDateString('pt-BR') const cid = report.cid ?? report.cid_code ?? report.cidCode ?? report.cie ?? '' const exam = report.exam ?? report.exame ?? report.especialidade ?? report.report_type ?? '' const diagnosis = report.diagnosis ?? report.diagnostico ?? report.diagnosis_text ?? report.diagnostico_text ?? '' const conclusion = report.conclusion ?? report.conclusao ?? report.conclusion_text ?? report.conclusao_text ?? '' const notesText = report.content ?? report.body ?? report.conteudo ?? report.notes ?? report.observacoes ?? '' // Extrair nome do médico let doctorName = '' if (doctor) { doctorName = doctor.full_name || doctor.name || doctor.fullName || doctor.doctor_name || '' } if (!doctorName) { const rd = report as any const tryKeys = [ 'doctor_name', 'doctor_full_name', 'doctorFullName', 'doctorName', 'requested_by_name', 'requested_by', 'requester_name', 'requester', 'created_by_name', 'created_by', 'executante', 'executante_name', ] for (const k of tryKeys) { const v = rd[k] if (v !== undefined && v !== null && String(v).trim() !== '') { doctorName = String(v) break } } } // Extrair nome do paciente let patientName = '' if (patient) { patientName = patient.full_name || patient.name || '' } // Montar HTML do documento element.innerHTML = `

RELATÓRIO MÉDICO

Data: ${reportDate}

${patientName ? `

Paciente: ${patientName}

` : ''} ${doctorName ? `

Profissional: ${doctorName}

` : ''}
${cid ? `

CID

${cid}

` : ''} ${exam ? `

EXAME / TIPO

${exam}

` : ''}
${diagnosis ? `

DIAGNÓSTICO

${diagnosis}

` : ''} ${conclusion ? `

CONCLUSÃO

${conclusion}

` : ''} ${notesText ? `

NOTAS DO PROFISSIONAL

${notesText}

` : ''}
Documento gerado em ${new Date().toLocaleString('pt-BR')}
` document.body.appendChild(element) // Capturar como canvas const canvas = await html2canvas(element, { scale: 2, useCORS: true, backgroundColor: '#ffffff', }) document.body.removeChild(element) // Converter para PDF const imgData = canvas.toDataURL('image/png') const pdf = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4', }) const imgWidth = 210 // A4 width in mm const pageHeight = 297 // A4 height in mm const imgHeight = (canvas.height * imgWidth) / canvas.width let heightLeft = imgHeight let position = 0 while (heightLeft >= 0) { pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight) heightLeft -= pageHeight position -= pageHeight if (heightLeft > 0) { pdf.addPage() } } // Download pdf.save(`laudo-${reportDate}-${doctorName || 'profissional'}.pdf`) } catch (error) { console.error('Erro ao gerar PDF:', error) alert('Erro ao gerar PDF. Tente novamente.') } } if (loading) { return (
Carregando laudo...
) } if (error || !report) { return (
{error || 'Laudo não encontrado.'}
) } // Extract fields with fallbacks const reportDate = new Date(report.report_date || report.created_at || Date.now()).toLocaleDateString('pt-BR') const cid = report.cid ?? report.cid_code ?? report.cidCode ?? report.cie ?? '' const exam = report.exam ?? report.exame ?? report.especialidade ?? report.report_type ?? '' const diagnosis = report.diagnosis ?? report.diagnostico ?? report.diagnosis_text ?? report.diagnostico_text ?? '' const conclusion = report.conclusion ?? report.conclusao ?? report.conclusion_text ?? report.conclusao_text ?? '' const notesHtml = report.content_html ?? report.conteudo_html ?? report.contentHtml ?? null const notesText = report.content ?? report.body ?? report.conteudo ?? report.notes ?? report.observacoes ?? '' // Extract doctor name with multiple fallbacks let doctorName = '' if (doctor) { doctorName = doctor.full_name || doctor.name || doctor.fullName || doctor.doctor_name || '' } if (!doctorName) { const rd = report as any const tryKeys = [ 'doctor_name', 'doctor_full_name', 'doctorFullName', 'doctorName', 'requested_by_name', 'requested_by', 'requester_name', 'requester', 'created_by_name', 'created_by', 'executante', 'executante_name', ] for (const k of tryKeys) { const v = rd[k] if (v !== undefined && v !== null && String(v).trim() !== '') { doctorName = String(v) break } } } return (
{/* Header Toolbar */}
{/* Left Section */}

Laudo Médico

{doctorName || 'Profissional'}

{/* Right Section */}
{/* Main Content Area */}
{/* Document Container */}
{/* Document Content */}
{/* Title */}

RELATÓRIO MÉDICO

Data: {reportDate}

{doctorName && (

Profissional:{' '} {doctorName}

)}
{/* Patient/Header Info */}
{patient && (

{patient.full_name || patient.name || 'N/A'}

)} {cid && (

{cid}

)} {exam && (

{exam}

)}
{/* Diagnosis Section */} {diagnosis && (

Diagnóstico

{diagnosis}
)} {/* Conclusion Section */} {conclusion && (

Conclusão

{conclusion}
)} {/* Notes/Content Section */} {(notesHtml || notesText) && (

Notas do Profissional

{notesHtml ? (
) : (
{notesText}
)}
)} {/* Signature Section */} {report.doctor_signature && (
Assinatura do profissional
{doctorName && (

{doctorName}

{doctor?.crm && (

CRM: {doctor.crm}

)}
)}
)} {/* Footer */}

Documento gerado em {new Date().toLocaleString('pt-BR')}

) }