import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:intl/intl.dart'; import '../../../../core/theme/app_colors.dart'; import '../../../../core/widgets/medical_modal.dart'; import '../../../config/presentation/store/config_store.dart'; import '../../services/prescription_pdf_service.dart'; class PrescriptionModalView extends StatefulWidget { final String patientName; final ConfigStore? configStore; const PrescriptionModalView({ super.key, required this.patientName, this.configStore, }); @override State createState() => _PrescriptionModalViewState(); } class _PrescriptionModalViewState extends State { late final TextEditingController _patientController; late final TextEditingController _prescriptionController; late final FocusNode _prescriptionFocusNode; late final ConfigStore _configStore; bool _isPrinting = false; String? _statusMessage; bool _hasError = false; @override void initState() { super.initState(); _patientController = TextEditingController(text: widget.patientName); _prescriptionController = TextEditingController(); _prescriptionFocusNode = FocusNode(); _configStore = widget.configStore ?? ConfigStore(); _configStore.loadConfig(); } @override void dispose() { _patientController.dispose(); _prescriptionController.dispose(); _prescriptionFocusNode.dispose(); super.dispose(); } void _insertBullet() { final text = _prescriptionController.text; final selection = _prescriptionController.selection; final bullet = text.isEmpty || text.endsWith('\n') ? '• ' : '\n• '; int start = selection.start; int end = selection.end; if (start < 0 || end < 0) { start = text.length; end = text.length; } final newText = text.replaceRange(start, end, bullet); final newOffset = start + bullet.length; _prescriptionController.value = TextEditingValue( text: newText, selection: TextSelection.collapsed(offset: newOffset), ); _prescriptionFocusNode.requestFocus(); } Future _handlePrint() async { final patient = _patientController.text.trim(); final prescription = _prescriptionController.text.trim(); if (patient.isEmpty) { setState(() { _statusMessage = 'Debe indicar el nombre del paciente.'; _hasError = true; }); return; } if (prescription.isEmpty) { setState(() { _statusMessage = 'Debe redactar los medicamentos e indicaciones de la receta.'; _hasError = true; }); return; } setState(() { _isPrinting = true; _statusMessage = 'Generando receta médica en formato oficial...'; _hasError = false; }); try { await PrescriptionPdfService.printPrescription( doctorName: _configStore.nombreDoctor, specialty: _configStore.especialidad, subspecialty: _configStore.descripEspecialidad, generalContact: _configStore.descripGeneral, patientName: patient, prescriptionText: prescription, ); if (mounted) { setState(() { _isPrinting = false; _statusMessage = 'Receta generada con éxito.'; _hasError = false; }); } } catch (e) { if (mounted) { setState(() { _isPrinting = false; _statusMessage = 'Error al generar la receta: $e'; _hasError = true; }); } } } @override Widget build(BuildContext context) { final formattedDate = DateFormat('dd/MM/yyyy').format(DateTime.now()); return Observer( builder: (_) { return MedicalModalDialog( maxWidth: 820, maxHeight: 650, title: 'Emisión de Receta Médica', titleIcon: Container( padding: const EdgeInsets.all(8), decoration: BoxDecoration( color: const Color(0xFF00A65A).withValues(alpha: 0.12), borderRadius: BorderRadius.circular(10), ), child: const Icon( Icons.medication_rounded, color: Color(0xFF00A65A), size: 20, ), ), subtitle: const Text( 'Redacte la prescripción para imprimir en talonario media carta institucional', style: TextStyle(fontSize: 12, color: AppColors.textMuted), ), bottomBar: Container( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12), decoration: const BoxDecoration( color: Color(0xFFF8FAFC), border: Border(top: BorderSide(color: Color(0xFFE2E8F0))), ), child: Row( children: [ Container( padding: const EdgeInsets.all(4), decoration: BoxDecoration( color: _hasError ? AppColors.error.withValues(alpha: 0.12) : const Color(0xFF00A65A).withValues(alpha: 0.12), shape: BoxShape.circle, ), child: Icon( _hasError ? Icons.error_outline_rounded : Icons.check_circle_outline_rounded, size: 15, color: _hasError ? AppColors.error : const Color(0xFF00A65A), ), ), const SizedBox(width: 8), Expanded( child: Text( _statusMessage ?? (_isPrinting ? 'Preparando documento para impresión...' : 'Listo para emitir la receta médica'), style: TextStyle( fontSize: 12, fontWeight: FontWeight.w600, color: _hasError ? AppColors.error : AppColors.textSecondary, ), ), ), Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(6), border: Border.all(color: const Color(0xFFE2E8F0)), ), child: const Row( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.keyboard_outlined, size: 12, color: AppColors.textMuted), SizedBox(width: 4), Text( 'ESC para salir', style: TextStyle( fontSize: 11, color: AppColors.textMuted, fontWeight: FontWeight.w500, ), ), ], ), ), const SizedBox(width: 12), ElevatedButton.icon( onPressed: _isPrinting ? null : _handlePrint, icon: _isPrinting ? const SizedBox( width: 16, height: 16, child: CircularProgressIndicator( strokeWidth: 2, color: Colors.white, ), ) : const Icon(Icons.print_rounded, size: 16), label: Text( _isPrinting ? 'Generando...' : 'Crear / Imprimir Receta', style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 12.5), ), style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFF00A65A), foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), elevation: 0, ), ), ], ), ), child: SingleChildScrollView( padding: const EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ // Membrete Informativo del Médico (Vista preliminar institucional) Container( padding: const EdgeInsets.all(16), decoration: BoxDecoration( color: const Color(0xFFF8FAFC), borderRadius: BorderRadius.circular(12), border: Border.all(color: const Color(0xFFE2E8F0)), ), child: Column( children: [ Text( _configStore.nombreDoctor.isNotEmpty ? _configStore.nombreDoctor : 'Dr. Luis A. Castro Sosa', textAlign: TextAlign.center, style: const TextStyle( fontSize: 18, fontWeight: FontWeight.w700, color: AppColors.textPrimary, letterSpacing: -0.3, ), ), if (_configStore.especialidad.isNotEmpty) ...[ const SizedBox(height: 2), Text( _configStore.especialidad.toUpperCase(), textAlign: TextAlign.center, style: const TextStyle( fontSize: 11.5, fontWeight: FontWeight.w600, color: AppColors.primary, letterSpacing: 0.5, ), ), ], if (_configStore.descripEspecialidad.isNotEmpty) ...[ const SizedBox(height: 2), Text( _configStore.descripEspecialidad.toUpperCase(), textAlign: TextAlign.center, style: const TextStyle( fontSize: 10, color: AppColors.textMuted, ), ), ], const SizedBox(height: 4), Text( 'Fecha: $formattedDate', style: const TextStyle( fontSize: 11, fontWeight: FontWeight.w500, color: AppColors.textSecondary, ), ), ], ), ), const SizedBox(height: 16), // Campo Paciente Row( children: [ Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), decoration: BoxDecoration( color: const Color(0xFF00A65A).withValues(alpha: 0.1), borderRadius: BorderRadius.circular(8), ), child: const Text( 'Rx', style: TextStyle( fontSize: 14, fontWeight: FontWeight.w800, color: Color(0xFF00A65A), ), ), ), const SizedBox(width: 12), Expanded( child: TextField( controller: _patientController, decoration: InputDecoration( labelText: 'Paciente', hintText: 'Nombre del paciente', isDense: true, floatingLabelBehavior: FloatingLabelBehavior.always, filled: true, fillColor: Colors.white, contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: Color(0xFFE2E8F0)), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: Color(0xFFE2E8F0)), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: const BorderSide(color: AppColors.primary, width: 1.5), ), ), style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600), ), ), ], ), const SizedBox(height: 16), // Barra de herramientas de redacción Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text( 'Medicamentos y Posología:', style: TextStyle( fontSize: 13, fontWeight: FontWeight.w700, color: AppColors.textPrimary, ), ), TextButton.icon( onPressed: _insertBullet, icon: const Icon(Icons.format_list_bulleted_rounded, size: 16), label: const Text('Insertar viñeta (•)', style: TextStyle(fontSize: 12)), style: TextButton.styleFrom( foregroundColor: AppColors.primary, padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), visualDensity: VisualDensity.compact, ), ), ], ), const SizedBox(height: 6), // Lienzo de prescripción TextField( controller: _prescriptionController, focusNode: _prescriptionFocusNode, maxLines: 12, minLines: 8, style: const TextStyle(fontSize: 13.5, height: 1.5, color: AppColors.textPrimary), decoration: InputDecoration( hintText: '1. Nombre del medicamento, concentración\n - Dosis y frecuencia (ej. Tomar 1 tableta cada 8 horas por 7 días)\n - Indicaciones especiales (con comidas, en ayunas, etc.)\n\n2. Siguiente medicamento...', hintStyle: const TextStyle(color: Color(0xFF94A3B8), fontSize: 13), filled: true, fillColor: Colors.white, contentPadding: const EdgeInsets.all(16), border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color: Color(0xFFE2E8F0)), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color: Color(0xFFE2E8F0)), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: const BorderSide(color: AppColors.primary, width: 1.5), ), ), ), ], ), ), ); }, ); } }