// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
//  add_edit_bloodwork_screen.dart
//  Screen for adding or editing bloodwork records
//
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:nokken/src/core/utils/get_labels.dart';
import 'package:nokken/src/features/bloodwork_tracker/models/bloodwork.dart';
import 'package:nokken/src/features/bloodwork_tracker/providers/bloodwork_state.dart';
import 'package:nokken/src/core/services/navigation/navigation_service.dart';
import 'package:nokken/src/core/ui/widgets/dialog_service.dart';
import 'package:nokken/src/core/ui/theme/app_icons.dart';
import 'package:nokken/src/core/ui/theme/app_theme.dart';
import 'package:nokken/src/core/ui/theme/app_colors.dart';
import 'package:nokken/src/core/ui/theme/app_text_styles.dart';
import 'package:nokken/src/core/ui/widgets/shared_widgets.dart';
import 'package:nokken/src/core/ui/widgets/dropdown_widgets.dart';
import 'package:nokken/src/core/utils/get_icons_colors.dart';
import 'package:nokken/src/core/utils/date_time_formatter.dart';

import 'widgets/add_edit_location_doctor.dart';

class AddEditBloodworkScreen extends ConsumerStatefulWidget {
  final Bloodwork? bloodwork;

  const AddEditBloodworkScreen({
    super.key,
    this.bloodwork,
  });

  @override
  ConsumerState<AddEditBloodworkScreen> createState() =>
      _AddEditBloodworkScreenState();
}

class _AddEditBloodworkScreenState
    extends ConsumerState<AddEditBloodworkScreen> {
  final _formKey = GlobalKey<FormState>();

  // Controllers that need disposal
  late final TextEditingController _locationController;
  late final TextEditingController _doctorController;
  late final TextEditingController _notesController;

  // List of hormone reading controllers
  final List<Map<String, dynamic>> _hormoneControllers = [];

  // State variables
  late DateTime _selectedDate;
  late TimeOfDay _selectedTime;
  late AppointmentType _selectedAppointmentType;
  bool _isLoading = false;

  // Available hormone types for dropdown
  final List<String> _availableHormoneTypes = HormoneTypes.getHormoneTypes();

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

  /// Initialize all form fields with either existing bloodwork data or defaults
  void _initializeFields() {
    // Initialize date and time
    if (widget.bloodwork?.date != null) {
      _selectedDate = widget.bloodwork!.date;
      _selectedTime = TimeOfDay.fromDateTime(widget.bloodwork!.date);
    } else {
      _selectedDate = DateTime.now();
      _selectedTime = TimeOfDay.now();
    }

    // Initialize appointment type
    _selectedAppointmentType =
        widget.bloodwork?.appointmentType ?? AppointmentType.bloodwork;

    _locationController = TextEditingController(
      text: widget.bloodwork?.location ?? '',
    );

    _doctorController = TextEditingController(
      text: widget.bloodwork?.doctor ?? '',
    );

    _notesController = TextEditingController(
      text: widget.bloodwork?.notes ?? '',
    );

    // Initialize hormone controllers
    _initializeHormoneControllers();
  }

  /// Initialize hormone reading controllers from existing bloodwork or defaults
  void _initializeHormoneControllers() {
    if (widget.bloodwork != null) {
      // Try to use hormone readings
      if (widget.bloodwork!.hormoneReadings.isNotEmpty) {
        for (final reading in widget.bloodwork!.hormoneReadings) {
          _addHormoneField(
            name: reading.name,
            value: reading.value.toString(),
            unit: reading.unit,
          );
        }
      }
    }

    // If no hormone fields were added, add an empty one
    if (_hormoneControllers.isEmpty) {
      _addHormoneField();
    }

    // Double-check all controller relationships are properly set up
    for (final controller in _hormoneControllers) {
      final nameController = controller['name'] as TextEditingController;
      final unitController = controller['unit'] as TextEditingController;

      // Verify unit is correct for the current hormone type
      final hormoneName = nameController.text;
      final expectedUnit = HormoneTypes.getDefaultUnit(hormoneName);

      // If unit doesn't match expected, update it
      if (expectedUnit.isNotEmpty && unitController.text != expectedUnit) {
        unitController.text = expectedUnit;
      }
    }
  }

  /// Add a new hormone field with optional preset values
  void _addHormoneField({String? name, String? value, String? unit}) {
    final nameController =
        TextEditingController(text: name ?? _availableHormoneTypes[0]);
    final valueController = TextEditingController(text: value ?? '');
    final unitController = TextEditingController(
      text: unit ??
          HormoneTypes.getDefaultUnit(name ?? _availableHormoneTypes[0]),
    );

    setState(() {
      _hormoneControllers.add({
        'name': nameController,
        'value': valueController,
        'unit': unitController,
      });
    });

    // Listener for hormone type changes
    nameController.addListener(() {
      // Get the current hormone name
      final hormoneName = nameController.text;

      // Get the default unit for this hormone
      final defaultUnit = HormoneTypes.getDefaultUnit(hormoneName);

      // Only update if we have a valid default unit
      if (defaultUnit.isNotEmpty) {
        // Force an update of the unit controller
        unitController.text = defaultUnit;

        // Make sure the UI reflects the change
        setState(() {});
      }
    });
  }

  /// Remove a hormone field at the specified index
  void _removeHormoneField(int index) {
    if (_hormoneControllers.length <= 1) {
      // Don't remove the last field
      return;
    }

    setState(() {
      // Dispose controllers
      _hormoneControllers[index]['name'].dispose();
      _hormoneControllers[index]['value'].dispose();
      _hormoneControllers[index]['unit'].dispose();

      // Remove from list
      _hormoneControllers.removeAt(index);
    });
  }

  // Clean up controllers to prevent memory leaks
  @override
  void dispose() {
    _locationController.dispose();
    _doctorController.dispose();
    _notesController.dispose();

    // Dispose all hormone controllers
    for (final controllers in _hormoneControllers) {
      controllers['name'].dispose();
      controllers['value'].dispose();
      controllers['unit'].dispose();
    }

    super.dispose();
  }

  /// Show date picker dialog and handle date selection
  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2000),
      lastDate: DateTime.now().add(const Duration(
          days: 365 * 2)), // Allow scheduling up to 2 years in future
    );
    if (picked != null && picked != _selectedDate) {
      setState(() {
        _selectedDate = picked;
      });
    }
  }

  /// Build time input field
  Widget _buildTimeInput(BuildContext context) {
    final isPM = _selectedTime.hour >= 12;
    final hour12 = _selectedTime.hour > 12
        ? _selectedTime.hour - 12
        : (_selectedTime.hour == 0 ? 12 : _selectedTime.hour);

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          // Hour input
          SizedBox(
            width: 45,
            child: TextFormField(
              initialValue: hour12.toString(),
              keyboardType: TextInputType.number,
              textAlign: TextAlign.center,
              decoration: AppTheme.defaultTextFieldDecoration,
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(2),
              ],
              onChanged: (value) {
                if (value.isNotEmpty) {
                  final newHour = int.parse(value);
                  if (newHour >= 1 && newHour <= 12) {
                    final hour24 = isPM
                        ? (newHour == 12 ? 12 : newHour + 12)
                        : (newHour == 12 ? 0 : newHour);
                    setState(() {
                      _selectedTime =
                          TimeOfDay(hour: hour24, minute: _selectedTime.minute);
                    });
                  }
                }
              },
            ),
          ),
          const Padding(
            padding: EdgeInsets.symmetric(horizontal: 8),
            child: Text(':', style: TextStyle(fontSize: 20)),
          ),
          // Minute input
          SizedBox(
            width: 45,
            child: TextFormField(
              initialValue: _selectedTime.minute.toString().padLeft(2, '0'),
              keyboardType: TextInputType.number,
              textAlign: TextAlign.center,
              decoration: AppTheme.defaultTextFieldDecoration,
              inputFormatters: [
                FilteringTextInputFormatter.digitsOnly,
                LengthLimitingTextInputFormatter(2),
              ],
              onChanged: (value) {
                if (value.isNotEmpty) {
                  final newMinute = int.parse(value);
                  if (newMinute >= 0 && newMinute < 60) {
                    setState(() {
                      _selectedTime = TimeOfDay(
                          hour: _selectedTime.hour, minute: newMinute);
                    });
                  }
                }
              },
            ),
          ),
          SharedWidgets.horizontalSpace(12),
          // AM/PM toggle
          TextButton(
            onPressed: () {
              final currentHour = _selectedTime.hour;
              final hour12 = currentHour > 12
                  ? currentHour - 12
                  : (currentHour == 0 ? 12 : currentHour);

              final newIsPM = !isPM;
              final newHour = newIsPM
                  ? (hour12 == 12 ? 12 : hour12 + 12)
                  : (hour12 == 12 ? 0 : hour12);

              setState(() {
                _selectedTime =
                    TimeOfDay(hour: newHour, minute: _selectedTime.minute);
              });
            },
            style: TextButton.styleFrom(
              padding: EdgeInsets.zero,
              side: BorderSide(color: AppColors.outline),
            ),
            child: Text(
              isPM ? 'PM' : 'AM',
              style: AppTextStyles.buttonText,
            ),
          ),
        ],
      ),
    );
  }

  /// Check if selected date is in the future
  bool _isDateInFuture() {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final selectedDate =
        DateTime(_selectedDate.year, _selectedDate.month, _selectedDate.day);
    return selectedDate.isAfter(today);
  }

  /// Build location and doctor fields
  Widget _buildLocationDoctorFields() {
    return LocationDoctorFields(
      locationController: _locationController,
      doctorController: _doctorController,
    );
  }

  /// Build hormone levels section for bloodwork
  Widget _buildHormoneLevelsSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Future date warning if applicable
        if (_isDateInFuture())
          Padding(
            padding: const EdgeInsets.only(bottom: 16.0),
            child: Container(
              padding: AppTheme.standardCardPadding,
              decoration: BoxDecoration(
                color: AppColors.info.withAlpha(20),
                borderRadius: BorderRadius.circular(4.0),
              ),
              child: Row(
                children: [
                  Icon(AppIcons.getIcon('info'), color: AppColors.info),
                  SharedWidgets.horizontalSpace(),
                  Expanded(
                    child: Text(
                      'This is a future date. Hormone levels can be added after the lab date occurs.',
                      style: TextStyle(color: AppColors.info),
                    ),
                  ),
                ],
              ),
            ),
          ),

        // List of hormone inputs
        ...List.generate(
          _hormoneControllers.length,
          (index) => HormoneInputRow(
            index: index,
            nameController: _hormoneControllers[index]['name'],
            valueController: _hormoneControllers[index]['value'],
            unitController: _hormoneControllers[index]['unit'],
            availableHormoneTypes: _availableHormoneTypes,
            onRemove: () => _removeHormoneField(index),
            canRemove: _hormoneControllers.length > 1,
          ),
        ),

        // Add button
        if (_hormoneControllers.length < 10 && !_isDateInFuture())
          Center(
            child: TextButton.icon(
              icon: Icon(AppIcons.getIcon('add')),
              label: const Text('Add Level'),
              onPressed: () => _addHormoneField(),
            ),
          ),
      ],
    );
  }

  /// Save or update bloodwork data
  Future<void> _saveBloodwork() async {
    // Validate form before proceeding
    if (!_formKey.currentState!.validate()) return;

    // Only validate hormone values for past/present dates with bloodwork appointment type
    if (!_isDateInFuture() &&
        _selectedAppointmentType == AppointmentType.bloodwork) {}

    // Show loading indicator
    setState(() => _isLoading = true);

    try {
      // Create a DateTime that includes both date and time
      final dateTime = DateTime(
        _selectedDate.year,
        _selectedDate.month,
        _selectedDate.day,
        _selectedTime.hour,
        _selectedTime.minute,
      );

      // Create bloodwork object from form data
      final bloodwork = Bloodwork(
        id: widget.bloodwork?.id, // null for new, existing id for updates
        date: dateTime,
        appointmentType: _selectedAppointmentType,
        hormoneReadings: _isDateInFuture()
            ? [] // No hormone readings for future dates
            : _getValidHormoneReadings(),
        location: _locationController.text.trim().isNotEmpty
            ? _locationController.text.trim()
            : null,
        doctor: _doctorController.text.trim().isNotEmpty
            ? _doctorController.text.trim()
            : null,
        notes: _notesController.text.trim().isNotEmpty
            ? _notesController.text.trim()
            : null,
      );

      // If bloodwork is null, we're adding new
      // Otherwise, we're updating existing
      if (widget.bloodwork == null) {
        await ref.read(bloodworkStateProvider.notifier).addBloodwork(bloodwork);
      } else {
        await ref
            .read(bloodworkStateProvider.notifier)
            .updateBloodwork(bloodwork);
      }

      // Return to bloodwork list screen
      if (mounted) {
        NavigationService.goBack(context);
      }
    } catch (e) {
      // Show error in snackbar if something goes wrong
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Error: $e'),
            backgroundColor: AppColors.error,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  /// Get valid hormone readings from the input fields
  List<HormoneReading> _getValidHormoneReadings() {
    final readings = <HormoneReading>[];

    for (final controller in _hormoneControllers) {
      final name = controller['name'].text;
      final valueText = controller['value'].text;
      final unit = controller['unit'].text;

      if (valueText.isNotEmpty) {
        final value = double.tryParse(valueText);
        if (value != null && value >= 0) {
          readings.add(HormoneReading(
            name: name,
            value: value,
            unit: unit.isNotEmpty ? unit : HormoneTypes.getDefaultUnit(name),
          ));
        }
      }
    }

    return readings;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          widget.bloodwork == null ? 'Add Appointment' : 'Edit Appointment',
        ),
        leading: IconButton(
          icon: Icon(AppIcons.getIcon('arrow_back')),
          onPressed: () => _handleBackButton(context, ref),
        ),
        actions: [
          // Show loading indicator or save button
          _isLoading
              ? const Center(
                  child: Padding(
                    padding: AppTheme.standardCardPadding,
                    child: CircularProgressIndicator(),
                  ),
                )
              : TextButton(
                  onPressed: _saveBloodwork,
                  child: Text(
                    'Save',
                    style: AppTextStyles.titleMedium,
                  ),
                ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: ListView(
          padding: AppTheme.standardCardPadding,
          children: [
            // Date selection
            SharedWidgets.basicCard(
              context: context,
              title: 'Date and Time',
              children: [
                ListTile(
                  leading: Icon(AppIcons.getIcon('calendar')),
                  title: Text(
                    DateTimeFormatter.formatDateDDMMYY(_selectedDate),
                  ),
                  onTap: () => _selectDate(context),
                ),
                // Add the time picker
                _buildTimeInput(context),
                _buildLocationDoctorFields(),
              ],
            ),
            SharedWidgets.verticalSpace(AppTheme.cardSpacing),

            AppointmentTypeSection(
              selectedAppointmentType: _selectedAppointmentType,
              onTypeChanged: (value) {
                if (value != null) {
                  setState(() {
                    _selectedAppointmentType = value;
                  });
                }
              },
            ),
            SharedWidgets.verticalSpace(AppTheme.cardSpacing),

            // Hormone levels (only shown for bloodwork type)
            if (_selectedAppointmentType == AppointmentType.bloodwork)
              SharedWidgets.basicCard(
                context: context,
                title: 'Hormone Levels',
                children: [
                  _buildHormoneLevelsSection(),
                ],
              ),
            SharedWidgets.verticalSpace(AppTheme.cardSpacing),

            // Notes section
            SharedWidgets.basicCard(
              context: context,
              title: 'Notes',
              children: [
                TextFormField(
                  controller: _notesController,
                  decoration: AppTheme.defaultTextFieldDecoration.copyWith(
                    hintText: 'Add any additional notes here',
                  ),
                  maxLines: 3,
                ),
              ],
            ),
            Row(
              children: [
                // Delete button on left (only if bloodwork exists)
                if (widget.bloodwork != null)
                  SizedBox(
                    height: 36,
                    child: ElevatedButton.icon(
                      icon: Icon(
                        AppIcons.getIcon('delete'),
                        size: 18,
                        color: AppColors.error,
                      ),
                      label: Text('Delete'),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: AppColors.error.withAlpha(40),
                        foregroundColor: AppColors.error,
                        padding: const EdgeInsets.symmetric(
                            horizontal: 12, vertical: 0),
                        minimumSize: Size.zero,
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      ),
                      onPressed: () => _showDeleteDialog(context, ref),
                    ),
                  ),

                // Push save button to the right
                const Spacer(),

                // Save button on right (always present)
                SizedBox(
                  height: 36,
                  child: ElevatedButton.icon(
                    icon: Icon(
                      AppIcons.getIcon('save'),
                      size: 18,
                      color: AppColors.primary,
                    ),
                    label: Text('Save'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppColors.primary.withAlpha(40),
                      foregroundColor: AppColors.primary,
                      padding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 0),
                      minimumSize: Size.zero,
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    ),
                    onPressed: () => _saveBloodwork(),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  bool _checkForUnsavedChanges() {
    // For new entries, if any field has content, there are unsaved changes
    if (widget.bloodwork == null) {
      // Check if any required field has been filled
      if (_locationController.text.isNotEmpty ||
          _doctorController.text.isNotEmpty ||
          _notesController.text.isNotEmpty) {
        return true;
      }

      // Check if any hormone reading has been entered
      for (final controller in _hormoneControllers) {
        if (controller['value'].text.isNotEmpty) {
          return true;
        }
      }

      // Check if date or time was modified from their defaults
      final now = DateTime.now();
      final today = DateTime(now.year, now.month, now.day);
      final selectedDate =
          DateTime(_selectedDate.year, _selectedDate.month, _selectedDate.day);
      if (selectedDate != today) {
        return true;
      }

      return false;
    }

    // For existing entries, compare with original values
    else {
      // Compare date
      final originalDate = widget.bloodwork!.date;
      final originalDay =
          DateTime(originalDate.year, originalDate.month, originalDate.day);
      final currentDay =
          DateTime(_selectedDate.year, _selectedDate.month, _selectedDate.day);

      if (originalDay != currentDay) {
        return true;
      }

      // Compare time
      final originalTime = TimeOfDay.fromDateTime(originalDate);
      if (originalTime.hour != _selectedTime.hour ||
          originalTime.minute != _selectedTime.minute) {
        return true;
      }

      // Compare appointment type
      if (widget.bloodwork!.appointmentType != _selectedAppointmentType) {
        return true;
      }

      // Compare text fields
      if (_locationController.text != (widget.bloodwork!.location ?? '')) {
        return true;
      }

      if (_doctorController.text != (widget.bloodwork!.doctor ?? '')) {
        return true;
      }

      if (_notesController.text != (widget.bloodwork!.notes ?? '')) {
        return true;
      }

      // Compare hormone readings
      if (_selectedAppointmentType == AppointmentType.bloodwork) {
        // Different number of readings
        if (_getValidHormoneReadings().length !=
            widget.bloodwork!.hormoneReadings.length) {
          return true;
        }

        // Compare each reading
        final currentReadings = _getValidHormoneReadings();
        final originalReadings = widget.bloodwork!.hormoneReadings;

        for (var i = 0; i < currentReadings.length; i++) {
          // Try to find a matching reading in original
          bool foundMatch = false;
          for (var orig in originalReadings) {
            if (currentReadings[i].name == orig.name) {
              foundMatch = true;
              if (currentReadings[i].value != orig.value ||
                  currentReadings[i].unit != orig.unit) {
                return true; // Value or unit differs
              }
            }
          }

          if (!foundMatch) {
            return true; // New reading added
          }
        }
      }

      return false; // No changes detected
    }
  }

  void _handleBackButton(BuildContext context, WidgetRef ref) {
    DialogService.handleBackWithUnsavedChanges(
      context: context,
      ref: ref,
      checkForUnsavedChanges: _checkForUnsavedChanges,
      saveFn: _saveBloodwork,
    );
  }

  Future<void> _showDeleteDialog(BuildContext context, WidgetRef ref) async {
    await DialogService.showDeleteDialog(
      context: context,
      ref: ref,
      itemName: GetLabels.getAppointmentTypeText(_selectedAppointmentType),
      onDelete: () async {
        await ref
            .read(bloodworkStateProvider.notifier)
            .deleteBloodwork(widget.bloodwork!.id);

        if (context.mounted) {
          NavigationService.goHome(context);
        }
      },
    );
  }
}

class AppointmentTypeSection extends ConsumerWidget {
  final AppointmentType selectedAppointmentType;
  final ValueChanged<AppointmentType?> onTypeChanged;

  const AppointmentTypeSection({
    super.key,
    required this.selectedAppointmentType,
    required this.onTypeChanged,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return SharedWidgets.basicCard(
      context: context,
      title: 'Appointment Type',
      children: [
        DropdownWidgets.customDropdownButtonFormField<AppointmentType>(
          value: selectedAppointmentType,
          decoration: AppTheme.defaultTextFieldDecoration.copyWith(),
          items: AppointmentType.values.map((type) {
            String description;

            switch (type) {
              case AppointmentType.bloodwork:
                description = 'record and track lab results';
                break;
              case AppointmentType.appointment:
                description = 'consultations and standard checkups';
                break;
              case AppointmentType.surgery:
                description = 'plan pre-surgery requirements (coming soon)';
                break;
            }

            return DropdownWidgets.dropdownItemWithDescription<AppointmentType>(
              value: type,
              description: description,
              child: Row(
                children: [
                  GetIconsColors.getAppointmentIconWithColor(type),
                  SharedWidgets.horizontalSpace(12),
                  Text(GetLabels.getAppointmentTypeText(type)),
                ],
              ),
            );
          }).toList(),
          onChanged: onTypeChanged,
        ),
      ],
    );
  }
}

// Convert HormoneInputRow from StatelessWidget to StatefulWidget
// to properly manage state and UI updates
class HormoneInputRow extends StatefulWidget {
  final int index;
  final TextEditingController nameController;
  final TextEditingController valueController;
  final TextEditingController unitController;
  final List<String> availableHormoneTypes;
  final VoidCallback? onRemove;
  final bool canRemove;

  const HormoneInputRow({
    super.key,
    required this.index,
    required this.nameController,
    required this.valueController,
    required this.unitController,
    required this.availableHormoneTypes,
    this.onRemove,
    this.canRemove = true,
  });

  @override
  State<HormoneInputRow> createState() => _HormoneInputRowState();
}

class _HormoneInputRowState extends State<HormoneInputRow> {
  // Store current values for comparison
  late String _currentHormoneType;

  @override
  void initState() {
    super.initState();
    _currentHormoneType = widget.nameController.text;

    // Add listener to hormone type controller
    widget.nameController.addListener(_onHormoneTypeChanged);
  }

  @override
  void dispose() {
    // Remove listener when widget is disposed
    widget.nameController.removeListener(_onHormoneTypeChanged);
    super.dispose();
  }

  // Called when hormone type changes
  void _onHormoneTypeChanged() {
    // Only process if the value actually changed
    if (_currentHormoneType != widget.nameController.text) {
      _currentHormoneType = widget.nameController.text;

      // Update unit based on hormone type
      final defaultUnit = HormoneTypes.getDefaultUnit(_currentHormoneType);
      if (defaultUnit.isNotEmpty) {
        // Update unit controller and current unit
        widget.unitController.text = defaultUnit;
        // Force UI update to reflect the new unit
        setState(() {});
      }
    }
  }

  // Helper method to get hormone descriptions
  String _getHormoneDescription(String hormoneType) {
    switch (hormoneType) {
      // Sex Hormones
      case 'Estradiol':
        return 'Primary estrogen - affects feminization and reproductive health';
      case 'Free Estradiol':
        return 'Active, unbound form of estradiol available to tissues';
      case 'Estrone':
        return 'Weaker estrogen that can convert to estradiol';
      case 'Estriol':
        return 'Estrogen primarily produced during pregnancy';
      case 'Testosterone':
        return 'Primary androgen - affects masculinization and many body functions';
      case 'Free Testosterone':
        return 'Unbound, active form of testosterone available to tissues';
      case 'Bioavailable Testosterone':
        return 'Testosterone that is not bound to SHBG and available to tissues';
      case 'DHT':
        return 'Potent androgen derived from testosterone, affects hair and skin';
      case 'Progesterone':
        return 'Reproductive hormone affecting mood, sleep, and tissue development';
      case 'SHBG':
        return 'Protein that binds sex hormones, affecting their availability';
      case 'Free Androgen Index':
        return 'Ratio of testosterone to SHBG, marker of androgen activity';
      case 'Androstenedione':
        return 'Precursor hormone that converts to testosterone and estrogen';
      case 'DHEA':
        return 'Adrenal hormone and precursor to sex hormones';
      case 'DHEA-S':
        return 'Sulfated form of DHEA with longer half-life, androgen precursor';
      case '17-OH Progesterone':
        return 'Precursor to cortisol and sex hormones';

      // Pituitary Hormones
      case 'FSH':
        return 'Regulates reproductive function and gamete production';
      case 'LH':
        return 'Triggers ovulation and stimulates sex hormone production';
      case 'Prolactin':
        return 'Affects breast tissue, milk production and reproductive function';
      case 'Growth Hormone':
        return 'Regulates growth, cell regeneration and metabolism';
      case 'IGF-1':
        return 'Mediates growth hormone effects on tissues';

      // Thyroid Hormones
      case 'TSH':
        return 'Controls thyroid function, often monitored during HRT';
      case 'Free T3':
        return 'Active, unbound form of T3 thyroid hormone';
      case 'Total T3':
        return 'Total amount of T3 in blood (bound and unbound)';
      case 'Free T4':
        return 'Active, unbound form of T4 thyroid hormone';
      case 'Total T4':
        return 'Total amount of T4 in blood (bound and unbound)';
      case 'Reverse T3':
        return 'Inactive form of T3, may increase during stress or illness';
      case 'Thyroid Peroxidase Antibodies':
        return 'Marker for autoimmune thyroid disease';
      case 'Thyroglobulin Antibodies':
        return 'Marker for autoimmune thyroid disease';
      case 'Thyroglobulin':
        return 'Storage protein for thyroid hormones';

      // Adrenal Hormones
      case 'Cortisol':
        return 'Stress hormone that regulates metabolism and immune response';
      case 'Cortisone':
        return 'Inactive form of cortisol';
      case 'Aldosterone':
        return 'Regulates sodium retention and potassium excretion';
      case 'Epinephrine':
        return 'Stress hormone (adrenaline) that increases heart rate and energy';
      case 'Norepinephrine':
        return 'Stress hormone (noradrenaline) affecting blood pressure and alertness';

      // Metabolic Markers
      case 'Insulin':
        return 'Regulates blood glucose levels, affected by HRT';
      case 'C-Peptide':
        return 'Marker of insulin production by the pancreas';
      case 'Leptin':
        return 'Regulates appetite and energy expenditure';
      case 'Adiponectin':
        return 'Regulates glucose levels and fatty acid breakdown';

      // Vitamin D and Calcium
      case 'Vitamin D (25-OH)':
        return 'Important for bone health, often monitored during HRT';
      case 'Vitamin D (1,25-OH)':
        return 'Active form of vitamin D';
      case 'Parathyroid Hormone':
        return 'Regulates calcium and phosphate levels';
      case 'Calcitonin':
        return 'Decreases blood calcium levels, counteracts parathyroid hormone';

      // Other Hormones
      case 'Melatonin':
        return 'Regulates sleep-wake cycles, may be affected by HRT';
      case 'AMH':
        return 'Marker of ovarian reserve, important in fertility assessment';
      case 'Inhibin B':
        return 'Marker of reproductive function in all sexes';
      case 'Activin':
        return 'Regulates FSH secretion and reproductive function';
      case 'Oxytocin':
        return 'Affects social bonding, uterine contractions, and milk ejection';
      case 'Vasopressin':
        return 'Regulates water retention and blood pressure';

      default:
        return 'Hormone level measurement';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Hormone type dropdown with descriptions
          Expanded(
            flex: 5,
            child: DropdownWidgets.customDropdownButtonFormField<String>(
              value: widget.nameController.text,
              decoration: AppTheme.defaultTextFieldDecoration,
              items: widget.availableHormoneTypes.map((type) {
                return DropdownWidgets.dropdownItemWithDescription<String>(
                  value: type,
                  description: _getHormoneDescription(type),
                  child: Text(type),
                );
              }).toList(),
              onChanged: (String? value) {
                if (value != null) {
                  // This will trigger _onHormoneTypeChanged via the listener
                  widget.nameController.text = value;
                }
              },
            ),
          ),

          SharedWidgets.horizontalSpace(4),

          // Hormone value input
          Expanded(
            flex: 2,
            child: TextFormField(
              controller: widget.valueController,
              keyboardType:
                  const TextInputType.numberWithOptions(decimal: true),
              decoration: AppTheme.defaultTextFieldDecoration,
              inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d*$')),
              ],
              style: AppTextStyles.bodySmall,
            ),
          ),

          SharedWidgets.horizontalSpace(4),

          // Unit input (with default)
          Expanded(
            flex: 2,
            child: TextFormField(
              controller: widget.unitController,
              decoration: AppTheme.defaultTextFieldDecoration,
              readOnly: true,
              style: AppTextStyles.bodySmall,
            ),
          ),

          // Remove button
          IconButton(
            icon: Icon(AppIcons.getIcon('remove_circle')),
            onPressed: widget.canRemove ? widget.onRemove : null,
            color: widget.canRemove ? AppColors.error : AppTheme.grey,
          ),
        ],
      ),
    );
  }
}
