// ABOUTME: Dedicated weight entry screen with comprehensive input form
// ABOUTME: Handles weight input validation, unit selection, 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/weight_entry.dart';
import '../models/settings/unit_settings.dart';
import '../widgets/validation/validated_number_field.dart';
import '../widgets/validation/validated_date_picker.dart';
import '../widgets/validation/error_display_widget.dart';
import '../utils/unit_converter.dart';
import '../utils/error_handler.dart';
import '../services/validation_service.dart';

class AddWeightScreen extends StatefulWidget {
  final WeightEntry? editEntry; // For editing existing entries

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

  @override
  State<AddWeightScreen> createState() => _AddWeightScreenState();
}

class _AddWeightScreenState extends State<AddWeightScreen> {
  final _formKey = GlobalKey<FormState>();
  final _notesController = TextEditingController();
  final _validationService = ValidationService.instance;
  
  double? _weight;
  WeightUnit _selectedUnit = WeightUnit.kg;
  DateTime _selectedDateTime = DateTime.now();
  String? _weightError;
  bool _isLoading = false;
  bool _isFormValid = false;

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

  void _initializeFormData() {
    if (widget.editEntry != null) {
      final entry = widget.editEntry!;
      _selectedUnit = WeightUnit.fromString(entry.originalUnit);
      _weight = entry.weightInOriginalUnit;
      _selectedDateTime = entry.timestamp;
      _notesController.text = entry.notes ?? '';
    }
  }

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

  void _onWeightChanged(double? weight) {
    setState(() {
      _weight = weight;
      _weightError = _validateWeight(weight);
      _updateFormValidity();
    });
  }

  void _onUnitChanged(WeightUnit unit) {
    setState(() {
      _selectedUnit = unit;
      _weightError = _validateWeight(_weight);
      _updateFormValidity();
    });
  }

  String? _validateWeight(double? weight) {
    if (weight == null || weight <= 0) {
      return 'Please enter a valid weight';
    }
    
    return ValidatedNumberFieldValidators.weightValidator(weight);
  }

  void _updateFormValidity() {
    setState(() {
      _isFormValid = _weight != null && _weightError == null;
    });
  }

  void _onDateTimeChanged(DateTime? dateTime) {
    if (dateTime != null) {
      setState(() {
        _selectedDateTime = dateTime;
      });
    }
  }

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

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

    final weightEntry = WeightEntry.fromUserInput(
      id: widget.editEntry?.id,
      weightValue: _weight!,
      unit: _selectedUnit.symbol,
      timestamp: _selectedDateTime,
      notes: _notesController.text.trim().isEmpty ? null : _notesController.text.trim(),
    );

    if (widget.editEntry != null) {
      context.read<HealthDataBloc>().add(UpdateWeightEntryEvent(weightEntry));
    } else {
      context.read<HealthDataBloc>().add(AddWeightEntryEvent(weightEntry));
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isEditing = widget.editEntry != null;
    
    return Scaffold(
      appBar: AppBar(
        title: Text(isEditing ? 'Edit Weight' : 'Add Weight'),
        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 
                      ? 'Weight updated successfully' 
                      : 'Weight 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: [
                // Weight input section
                Card(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          'Weight',
                          style: theme.textTheme.titleMedium?.copyWith(
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        const SizedBox(height: 16),
                        ValidatedNumberField(
                          initialValue: _weight,
                          label: 'Weight',
                          suffix: _selectedUnit.symbol,
                          onChanged: _onWeightChanged,
                          validator: ValidatedNumberFieldValidators.weightValidator,
                          minValue: 20.0, // Medical minimum (44 lbs)
                          maxValue: 635.0, // Medical maximum (~1400 lbs)
                          decimalPlaces: 1,
                          isRequired: true,
                          showWarnings: false, // Disable range-based warnings, use validator instead
                        ),
                        const SizedBox(height: 16),
                        Row(
                          children: [
                            Text(
                              'Unit: ',
                              style: theme.textTheme.bodyMedium,
                            ),
                            DropdownButton<WeightUnit>(
                              value: _selectedUnit,
                              items: WeightUnit.values.map((unit) {
                                return DropdownMenuItem(
                                  value: unit,
                                  child: Text(unit.symbol),
                                );
                              }).toList(),
                              onChanged: (unit) {
                                if (unit != null) _onUnitChanged(unit);
                              },
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
                const SizedBox(height: 16),
                
                // Date and time selection
                Card(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: ValidatedDatePicker(
                      label: 'Date & Time',
                      initialDate: _selectedDateTime,
                      onChanged: _onDateTimeChanged,
                      showTimeSelection: true,
                      firstDate: DateTime.now().subtract(const Duration(days: 365 * 2)),
                      lastDate: DateTime.now(),
                      isRequired: true,
                    ),
                  ),
                ),
                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 || !_isFormValid) ? null : _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 Weight' : 'Save Weight',
                            style: const TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  void _showDeleteConfirmation() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Delete Weight Entry'),
        content: const Text(
          'Are you sure you want to delete this weight 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(DeleteWeightEntryEvent(widget.editEntry!.id!));
    }
  }
}
