import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import html2pdf from 'html2pdf.js';
import './styleMedico/NovoRelatorioAudio.css';

const NovoRelatorioAudio = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  
  const [formData, setFormData] = useState({
    paciente_nome: '',
    data_exame: new Date().toISOString().split('T')[0],
    exam: '',
    diagnostico: '',
    conclusao: '',
    medico_nome: 'Dr.______________________'
  });

  const handleAudioUpload = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    setLoading(true);
    const data = new FormData();
    data.append('audio', file);

    try {
      const response = await fetch('http://localhost:3001/api/transcrever-relatorio', {
        method: 'POST',
        body: data,
      });

      if (!response.ok) throw new Error('Erro na comunicação com a API');

      const result = await response.json();

      setFormData(prev => ({
        ...prev,
        exam: result.exam || prev.exam,
        diagnostico: result.diagnostico || prev.diagnostico,
        conclusao: result.conclusao || prev.conclusao
      }));

    } catch (error) {
      console.error(error);
      alert("Erro: Verifique se o backend (porta 3001) está rodando.");
    } finally {
      setLoading(false);
      e.target.value = null; 
    }
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  const handlePrintPDF = () => {
    const element = document.getElementById('documento-final');
    const opt = {
      margin: 0,
      filename: `Laudo_${formData.paciente_nome || 'SemNome'}.pdf`,
      image: { type: 'jpeg', quality: 0.98 },
      html2canvas: { scale: 2 },
      jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
    };
    html2pdf().set(opt).from(element).save();
  };

  return (
    <div className="ai-editor-container">
      
      <div className="editor-sidebar">
        <div>
            <h4><i className="bi bi-robot me-2"></i>AI Report</h4>
            <p className="text-muted small">Gerador de laudos automatizado</p>
        </div>

        <div className="ai-upload-box">
             {loading ? (
                <div className="spinner-border text-info" role="status"></div>
             ) : (
                 <>
                    <label htmlFor="audioFile" style={{cursor:'pointer', width:'100%', display:'block'}}>
                        <i className="bi bi-mic fs-2 text-info"></i>
                        <div style={{color:'#fff', fontWeight:'bold', marginTop:'10px'}}>Gravar / Enviar Áudio</div>
                        <div className="small text-muted mt-1">Clique para selecionar</div>
                    </label>
                    <input 
                        id="audioFile" 
                        type="file" 
                        accept="audio/*" 
                        style={{display:'none'}} 
                        onChange={handleAudioUpload}
                    />
                 </>
             )}
        </div>

        <hr className="border-secondary" />

        <div className="form-group">
            <label>NOME DO PACIENTE</label>
            <input 
                type="text" 
                name="paciente_nome" 
                className="form-control dark-input" 
                value={formData.paciente_nome} 
                onChange={handleChange}
                placeholder="Ex: Maria Silva"
            />
        </div>

        <div className="form-group">
            <label>EXAME REALIZADO</label>
            <input 
                type="text" 
                name="exam" 
                className="form-control dark-input" 
                value={formData.exam} 
                onChange={handleChange}
            />
        </div>

        <div className="form-group">
            <label>DIAGNÓSTICO (TEXTO)</label>
            <textarea 
                name="diagnostico" 
                rows="5" 
                className="form-control dark-input" 
                value={formData.diagnostico} 
                onChange={handleChange}
            ></textarea>
        </div>

        <div className="form-group">
            <label>CONCLUSÃO</label>
            <textarea 
                name="conclusao" 
                rows="3" 
                className="form-control dark-input" 
                value={formData.conclusao} 
                onChange={handleChange}
            ></textarea>
        </div>

        <div className="mt-auto d-flex gap-2">
            <button className="btn btn-outline-light flex-grow-1" onClick={() => navigate(-1)}>Voltar</button>
            <button className="btn btn-info flex-grow-1 fw-bold" onClick={handlePrintPDF}>
                <i className="bi bi-printer me-2"></i>PDF
            </button>
        </div>
      </div>

      <div className="preview-area">
        <div id="documento-final" className="paper-a4">
            
            <div style={{borderBottom: '2px solid #000', paddingBottom: '20px', marginBottom: '30px', display:'flex', justifyContent:'space-between'}}>
                <div>
                    <h2 style={{margin:0, fontSize:'18pt', fontWeight:'bold'}}>CLÍNICA RISE UP</h2>
                    <p style={{margin:0, fontSize:'10pt'}}>Excelência em Diagnóstico por Imagem</p>
                </div>
                <div style={{textAlign:'right', fontSize:'10pt'}}>
                    <p style={{margin:0}}><strong>{formData.medico_nome}</strong></p>
                    <p style={{margin:0}}>CRM/SP 123456</p>
                    <p style={{margin:0}}>{new Date().toLocaleDateString()}</p>
                </div>
            </div>

            <div style={{backgroundColor:'#f8f9fa', padding:'15px', borderRadius:'4px', marginBottom:'30px'}}>
                <table style={{width:'100%', fontSize:'11pt'}}>
                    <tbody>
                        <tr>
                            <td style={{width:'15%', fontWeight:'bold'}}>Paciente:</td>
                            <td>{formData.paciente_nome || '__________________________'}</td>
                        </tr>
                        <tr>
                            <td style={{fontWeight:'bold'}}>Exame:</td>
                            <td>{formData.exam || '__________________________'}</td>
                        </tr>
                        <tr>
                            <td style={{fontWeight:'bold'}}>Data:</td>
                            <td>{new Date(formData.data_exame).toLocaleDateString('pt-BR')}</td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div className="laudo-body">
                <h4 style={{textTransform:'uppercase', borderBottom:'1px solid #ccc', paddingBottom:'5px', marginBottom:'15px'}}>Relatório Médico</h4>
                
                <p style={{fontWeight:'bold', marginBottom:'5px'}}>Análise:</p>
                <p style={{marginBottom:'25px', textAlign:'justify', whiteSpace:'pre-wrap'}}>
                    {formData.diagnostico || <span style={{color:'#ccc'}}>O diagnóstico aparecerá aqui após o processamento do áudio...</span>}
                </p>

                <p style={{fontWeight:'bold', marginBottom:'5px'}}>Conclusão:</p>
                <p style={{marginBottom:'40px', textAlign:'justify', fontWeight:'500'}}>
                    {formData.conclusao}
                </p>
            </div>

            <div style={{marginTop:'50px', textAlign:'center', pageBreakInside:'avoid'}}>
                <p style={{marginBottom:0}}>________________________________________</p>
                <p style={{fontWeight:'bold', margin:0}}>{formData.medico_nome}</p>
                <p style={{fontSize:'10pt', color:'#666'}}>Assinatura Eletrônica</p>
            </div>

        </div>
      </div>
    </div>
  );
};

export default NovoRelatorioAudio;