// ABOUTME: Dedicated blood pressure entry screen with comprehensive input form
// ABOUTME: Handles BP input validation, medical categorization, date/time picker, and notes

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../bloc/health_data_bloc.dart';
import '../bloc/health_data_event.dart';
import '../bloc/health_data_state.dart';
import '../models/blood_pressure_entry.dart';
import '../widgets/bp_input_widget.dart';
import '../widgets/bp_category_indicator.dart';
import '../utils/blood_pressure_utils.dart';
import '../utils/unit_converter.dart';
import '../utils/error_handler.dart';

class AddBloodPressureScreen extends StatefulWidget {
  final BloodPressureEntry? editEntry; // For editing existing entries

  const AddBloodPressureScreen({
    super.key,
    this.editEntry,
  });

  @override
  State<AddBloodPressureScreen> createState() => _AddBloodPressureScreenState();
}

class _AddBloodPressureScreenState extends State<AddBloodPressureScreen> {
  final _formKey = GlobalKey<FormState>();
  final _notesController = TextEditingController();
  
  int? _systolic;
  int? _diastolic;
  DateTime _selectedDateTime = DateTime.now();
  String? _systolicError;
  String? _diastolicError;
  String? _globalError;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _initializeFormData();
  }

  void _initializeFormData() {
    if (widget.editEntry != null) {
      final entry = widget.editEntry!;
      _systolic = entry.systolic;
      _diastolic = entry.diastolic;
      _selectedDateTime = entry.timestamp;
      _notesController.text = entry.notes ?? '';
    }
  }

  @override
  void dispose() {
    _notesController.dispose();
    super.dispose();
  }

  void _onSystolicChanged(int? systolic) {
    setState(() {
      _systolic = systolic;
      _systolicError = BloodPressureUtils.validateSystolic(systolic);
      _globalError = BloodPressureUtils.validateBloodPressure(_systolic, _diastolic);
    });
  }

  void _onDiastolicChanged(int? diastolic) {
    setState(() {
      _diastolic = diastolic;
      _diastolicError = BloodPressureUtils.validateDiastolic(diastolic);
      _globalError = BloodPressureUtils.validateBloodPressure(_systolic, _diastolic);
    });
  }

  void _selectDateTime() async {
    final date = await showDatePicker(
      context: context,
      initialDate: _selectedDateTime,
      firstDate: DateTime(2000),
      lastDate: DateTime.now(),
      helpText: 'Select measurement date',
    );
    
    if (date != null && mounted) {
      final time = await showTimePicker(
        context: context,
        initialTime: TimeOfDay.fromDateTime(_selectedDateTime),
        helpText: 'Select measurement time',
      );
      
      if (time != null && mounted) {
        setState(() {
          _selectedDateTime = DateTime(
            date.year,
            date.month,
            date.day,
            time.hour,
            time.minute,
          );
        });
      }
    }
  }

  bool get _hasValidInput {
    return _systolic != null && 
           _diastolic != null &&
           _systolicError == null && 
           _diastolicError == null && 
           _globalError == null;
  }

  void _submitForm() {
    if (!_hasValidInput) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Please correct the errors before saving'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    setState(() {
      _isLoading = true;
    });

    final bpEntry = BloodPressureEntry(
      id: widget.editEntry?.id,
      systolic: _systolic!,
      diastolic: _diastolic!,
      timestamp: _selectedDateTime,
      notes: _notesController.text.trim().isEmpty ? null : _notesController.text.trim(),
    );

    if (widget.editEntry != null) {
      context.read<HealthDataBloc>().add(UpdateBloodPressureEntryEvent(bpEntry));
    } else {
      context.read<HealthDataBloc>().add(AddBloodPressureEntryEvent(bpEntry));
    }
  }

  void _showEmergencyDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.warning, color: Colors.red),
            SizedBox(width: 8),
            Text('Medical Emergency'),
          ],
        ),
        content: Text(
          'These blood pressure readings indicate a hypertensive crisis. You should seek immediate medical attention.\n\nDo you still want to record this reading?',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: Text('Cancel'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.of(context).pop(true);
              _submitForm();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
            ),
            child: Text('Record Anyway'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isEditing = widget.editEntry != null;
    
    return Scaffold(
      appBar: AppBar(
        title: Text(isEditing ? 'Edit Blood Pressure' : 'Add Blood Pressure'),
        backgroundColor: theme.colorScheme.surface,
        foregroundColor: theme.colorScheme.onSurface,
        elevation: 0,
        actions: [
          if (isEditing)
            IconButton(
              icon: const Icon(Icons.delete, color: Colors.red),
              onPressed: _showDeleteConfirmation,
            ),
        ],
      ),
      body: BlocListener<HealthDataBloc, HealthDataState>(
        listener: (context, state) {
          setState(() {
            _isLoading = false;
          });

          if (state is HealthDataOperationSuccess) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(
                  isEditing 
                      ? 'Blood pressure updated successfully' 
                      : 'Blood pressure added successfully',
                ),
                backgroundColor: Colors.green,
              ),
            );
            Navigator.of(context).pop(true); // Return true to indicate success
          } else if (state is HealthDataError) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(ErrorHandler.getErrorMessage(state.message)),
                backgroundColor: Colors.red,
              ),
            );
          }
        },
        child: Form(
          key: _formKey,
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Blood pressure input section
                Card(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: BloodPressureInputWidget(
                      initialSystolic: _systolic,
                      initialDiastolic: _diastolic,
                      onSystolicChanged: _onSystolicChanged,
                      onDiastolicChanged: _onDiastolicChanged,
                      systolicError: _systolicError,
                      diastolicError: _diastolicError,
                      globalError: _globalError,
                    ),
                  ),
                ),
                const SizedBox(height: 16),

                // Category preview
                if (_hasValidInput) ...[
                  BloodPressureCategoryIndicator(
                    entry: BloodPressureEntry(
                      timestamp: _selectedDateTime,
                      systolic: _systolic!,
                      diastolic: _diastolic!,
                    ),
                    showDescription: true,
                  ),
                  const SizedBox(height: 16),
                ],
                
                // Date and time selection
                Card(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Date & Time',
                          style: theme.textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        const SizedBox(height: 8),
                        InkWell(
                          onTap: _selectDateTime,
                          child: Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 12,
                              vertical: 16,
                            ),
                            decoration: BoxDecoration(
                              border: Border.all(
                                color: theme.colorScheme.outline,
                              ),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Row(
                              children: [
                                Icon(
                                  Icons.calendar_today,
                                  color: theme.colorScheme.onSurfaceVariant,
                                ),
                                const SizedBox(width: 12),
                                Expanded(
                                  child: Text(
                                    UnitConverter.formatDateTime(_selectedDateTime),
                                    style: theme.textTheme.bodyLarge,
                                  ),
                                ),
                                Icon(
                                  Icons.edit,
                                  color: theme.colorScheme.onSurfaceVariant,
                                  size: 20,
                                ),
                              ],
                            ),
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          'Tap to change date and time',
                          style: theme.textTheme.bodySmall?.copyWith(
                            color: theme.colorScheme.onSurfaceVariant,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                const SizedBox(height: 16),
                
                // Notes section
                Card(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Notes (Optional)',
                          style: theme.textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        const SizedBox(height: 8),
                        TextField(
                          controller: _notesController,
                          decoration: InputDecoration(
                            hintText: 'Add any notes about this measurement...',
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(8),
                            ),
                            contentPadding: const EdgeInsets.all(12),
                          ),
                          maxLines: 3,
                          maxLength: 500,
                        ),
                      ],
                    ),
                  ),
                ),
                const SizedBox(height: 24),
                
                // Submit button
                SizedBox(
                  width: double.infinity,
                  child: ElevatedButton(
                    onPressed: _isLoading ? null : () {
                      if (_hasValidInput && BloodPressureUtils.areValuesEmergency(_systolic, _diastolic)) {
                        _showEmergencyDialog();
                      } else {
                        _submitForm();
                      }
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: theme.colorScheme.primary,
                      foregroundColor: theme.colorScheme.onPrimary,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    child: _isLoading
                        ? const SizedBox(
                            height: 20,
                            width: 20,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                            ),
                          )
                        : Text(
                            isEditing ? 'Update Blood Pressure' : 'Save Blood Pressure',
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                  ),
                ),
                
                // Tips section
                const SizedBox(height: 16),
                Card(
                  color: theme.colorScheme.surfaceVariant.withOpacity(0.3),
                  child: Padding(
                    padding: const EdgeInsets.all(12),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Icon(
                              Icons.lightbulb_outline,
                              color: theme.colorScheme.primary,
                              size: 18,
                            ),
                            const SizedBox(width: 8),
                            Text(
                              'Measurement Tips',
                              style: theme.textTheme.titleSmall?.copyWith(
                                fontWeight: FontWeight.w600,
                                color: theme.colorScheme.primary,
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 8),
                        Text(
                          '• Rest for 5 minutes before measuring\n'
                          '• Sit with feet flat on the floor\n'
                          '• Use the same arm each time\n'
                          '• Avoid caffeine, exercise, or smoking beforehand',
                          style: theme.textTheme.bodySmall?.copyWith(
                            color: theme.colorScheme.onSurfaceVariant,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _showDeleteConfirmation() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Delete Blood Pressure Entry'),
        content: const Text(
          'Are you sure you want to delete this blood pressure entry? This action cannot be undone.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              _deleteEntry();
            },
            style: TextButton.styleFrom(
              foregroundColor: Colors.red,
            ),
            child: const Text('Delete'),
          ),
        ],
      ),
    );
  }

  void _deleteEntry() {
    if (widget.editEntry != null) {
      setState(() {
        _isLoading = true;
      });
      context.read<HealthDataBloc>().add(DeleteBloodPressureEntryEvent(widget.editEntry!.id!));
    }
  }
}
