// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
// add_edit_injection_details.dart
//
import 'package:flutter/material.dart';
import 'package:flutter/services.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/ui/theme/app_theme.dart';
import 'package:nokken/src/core/ui/theme/app_colors.dart';
import 'package:nokken/src/core/ui/theme/app_icons.dart';
import 'package:nokken/src/core/ui/theme/app_text_styles.dart';
import 'package:nokken/src/core/services/navigation/navigation_service.dart';
import 'package:nokken/src/features/medication_tracker/models/medication.dart';

/// Injection Details Section - Only shown for injection medications
class InjectionDetailsSection extends StatelessWidget {
  final InjectionDetails injectionDetails;
  final Function({
    String? drawingNeedleType,
    int? drawingNeedleCount,
    int? drawingNeedleRefills,
    String? injectingNeedleType,
    int? injectingNeedleCount,
    int? injectingNeedleRefills,
    String? syringeType,
    int? syringeCount,
    int? syringeRefills,
    String? injectionSiteNotes,
    InjectionFrequency? frequency,
    InjectionSubtype? subtype,
    InjectionSiteRotation? siteRotation,
  }) onDetailsChanged;

  const InjectionDetailsSection({
    super.key,
    required this.injectionDetails,
    required this.onDetailsChanged,
  });

  @override
  Widget build(BuildContext context) {
    return SharedWidgets.basicCard(
      context: context,
      title: 'Injection Details',
      children: [
        // Injection subtype dropdown
        DropdownWidgets.customDropdownButtonFormField<InjectionSubtype>(
          value: injectionDetails.subtype,
          decoration: AppTheme.defaultTextFieldDecoration.copyWith(),
          items: InjectionSubtype.values.map((subtype) {
            String displayName;
            IconData iconData;
            String description; // Add description variable

            switch (subtype) {
              case InjectionSubtype.intravenous:
                displayName = 'Intravenous (IV)';
                iconData = Icons.water_drop_outlined;
                description = 'delivered directly into a vein';
                break;
              case InjectionSubtype.intramuscular:
                displayName = 'Intramuscular (IM)';
                iconData = Icons.fitness_center_outlined;
                description = 'delivered into muscle tissue';
                break;
              case InjectionSubtype.subcutaneous:
                displayName = 'Subcutaneous (SC)';
                iconData = Icons.layers_outlined;
                description = 'delivered into the fatty layer beneath the skin';
                break;
            }

            return DropdownWidgets.dropdownItemWithDescription<
                InjectionSubtype>(
              value: subtype,
              description: description,
              child: Row(
                children: [
                  Icon(iconData, size: 20, color: AppColors.injection),
                  SharedWidgets.horizontalSpace(12),
                  Text(displayName),
                ],
              ),
            );
          }).toList(),
          onChanged: (value) {
            if (value != null) {
              onDetailsChanged(subtype: value);
            }
          },
        ),
        SharedWidgets.verticalSpace(),

        // Frequency Dropdown
        DropdownWidgets.customDropdownButtonFormField<InjectionFrequency>(
          value: injectionDetails.frequency,
          decoration: AppTheme.defaultTextFieldDecoration.copyWith(),
          items: InjectionFrequency.values.map((freq) {
            String displayText;
            IconData iconData;

            switch (freq) {
              case InjectionFrequency.weekly:
                displayText = 'Weekly';
                iconData = Icons.calendar_view_week_outlined;
                break;
              case InjectionFrequency.biweekly:
                displayText = 'Every 2 Weeks';
                iconData = Icons.calendar_month_outlined;
                break;
            }

            return DropdownMenuItem(
              value: freq,
              child: Row(
                children: [
                  Icon(iconData, size: 20, color: AppColors.injection),
                  SharedWidgets.horizontalSpace(12),
                  Text(displayText),
                ],
              ),
            );
          }).toList(),
          onChanged: (value) {
            if (value != null) {
              onDetailsChanged(frequency: value);
            }
          },
        ),
        SharedWidgets.verticalSpace(AppTheme.tripleSpacing),

        // Injection Site Rotation Section
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton.icon(
                  icon: Icon(AppIcons.getIcon('edit')),
                  label: const Text('Manage Sites'),
                  onPressed: () {
                    NavigationService.goToInjectionSiteTracker(
                      context,
                      initialRotation: injectionDetails.siteRotation,
                      onSave: (rotation) {
                        onDetailsChanged(siteRotation: rotation);
                      },
                    );
                  },
                ),
              ],
            ),
            SharedWidgets.verticalSpace(),
            _buildNextSitePreview(context),
          ],
        ),
        SharedWidgets.verticalSpace(AppTheme.tripleSpacing),

        _buildSuppliesSection(
          context,
          title: 'Syringes',
          typeValue: injectionDetails.syringeType,
          countValue: injectionDetails.syringeCount,
          refillsValue: injectionDetails.syringeRefills,
          onTypeChanged: (value) => onDetailsChanged(syringeType: value),
          onCountChanged: (value) => onDetailsChanged(syringeCount: value),
          onRefillsChanged: (value) => onDetailsChanged(syringeRefills: value),
          typeHint: 'e.g., 3mL Luer Lock',
        ),

        SharedWidgets.verticalSpace(AppTheme.doubleSpacing),

// Drawing Needles Section
        _buildSuppliesSection(
          context,
          title: 'Drawing Needles',
          typeValue: injectionDetails.drawingNeedleType,
          countValue: injectionDetails.drawingNeedleCount,
          refillsValue: injectionDetails.drawingNeedleRefills,
          onTypeChanged: (value) => onDetailsChanged(drawingNeedleType: value),
          onCountChanged: (value) =>
              onDetailsChanged(drawingNeedleCount: value),
          onRefillsChanged: (value) =>
              onDetailsChanged(drawingNeedleRefills: value),
          typeHint: 'e.g., 18G 1-inch',
        ),

        SharedWidgets.verticalSpace(AppTheme.doubleSpacing),

// Injecting Needles Section
        _buildSuppliesSection(
          context,
          title: 'Injecting Needles',
          typeValue: injectionDetails.injectingNeedleType,
          countValue: injectionDetails.injectingNeedleCount,
          refillsValue: injectionDetails.injectingNeedleRefills,
          onTypeChanged: (value) =>
              onDetailsChanged(injectingNeedleType: value),
          onCountChanged: (value) =>
              onDetailsChanged(injectingNeedleCount: value),
          onRefillsChanged: (value) =>
              onDetailsChanged(injectingNeedleRefills: value),
          typeHint: 'e.g., 23G 1.5-inch',
        ),

// Injection Site Notes
/*        SharedWidgets.verticalSpace(AppTheme.doubleSpacing),
        TextFormField(
          initialValue: injectionDetails.injectionSiteNotes,
          decoration: AppTheme.defaultTextFieldDecoration.copyWith(
            labelText: 'Injection Site Notes',
          ),
          maxLines: 2,
          onChanged: (value) => onDetailsChanged(injectionSiteNotes: value),
        ),*/
      ],
    );
  }

  Widget _buildSuppliesSection(
    BuildContext context, {
    required String title,
    required String typeValue,
    required int countValue,
    required int refillsValue,
    required Function(String) onTypeChanged,
    required Function(int) onCountChanged,
    required Function(int) onRefillsChanged,
    required String typeHint,
    String? description,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Section title with optional description
        Row(
          children: [
            Text(
              title,
              style: Theme.of(context).textTheme.titleSmall?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
            ),
            if (description != null)
              Tooltip(
                message: description,
                child: Padding(
                  padding: const EdgeInsets.only(left: 8.0),
                  child: Icon(
                    Icons.info_outline,
                    size: 16,
                    color: AppColors.info,
                  ),
                ),
              ),
          ],
        ),
        SharedWidgets.verticalSpace(),

        // Type field
        TextFormField(
          initialValue: typeValue,
          decoration: AppTheme.defaultTextFieldDecoration.copyWith(
            labelText: 'Type',
            hintText: typeHint,
          ),
          onChanged: onTypeChanged,
        ),
        SharedWidgets.verticalSpace(),

        // Count and Refills fields in a row
        Row(
          children: [
            // Current count field
            Expanded(
              child: TextFormField(
                initialValue: countValue.toString(),
                keyboardType: TextInputType.number,
                inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                decoration: AppTheme.defaultTextFieldDecoration.copyWith(
                  labelText: 'Quantity',
                ),
                onChanged: (value) {
                  final newValue = int.tryParse(value) ?? 0;
                  if (newValue >= 0) {
                    onCountChanged(newValue);
                  }
                },
              ),
            ),
            SharedWidgets.horizontalSpace(),

            // Refills count field
            Expanded(
              child: TextFormField(
                initialValue: refillsValue.toString(),
                keyboardType: TextInputType.number,
                inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                decoration: AppTheme.defaultTextFieldDecoration.copyWith(
                  labelText: 'Refill At',
                ),
                onChanged: (value) {
                  final newValue = int.tryParse(value) ?? 0;
                  if (newValue >= 0) {
                    onRefillsChanged(newValue);
                  }
                },
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// Build the next injection site preview
  Widget _buildNextSitePreview(BuildContext context) {
    if (injectionDetails.siteRotation == null ||
        injectionDetails.siteRotation!.sites.isEmpty) {
      return Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: AppColors.info.withAlpha(20),
          borderRadius: BorderRadius.circular(8),
        ),
        child: const Row(
          children: [
            Icon(Icons.info_outline),
            SizedBox(width: 8),
            Expanded(
              child: Text(
                'No injection sites configured. Tap "Manage Sites" to set up site rotation.',
                style: TextStyle(fontStyle: FontStyle.italic),
              ),
            ),
          ],
        ),
      );
    }

    final nextSite = injectionDetails.siteRotation!.nextSite;
    final bodyAreaText =
        nextSite.bodyArea == InjectionBodyArea.abdomen ? 'Abdomen' : 'Thigh';

    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: AppColors.tertiary.withAlpha(20),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: AppColors.tertiary),
      ),
      child: Row(
        children: [
          Icon(
            Icons.arrow_circle_right,
            color: AppColors.tertiary,
          ),
          SharedWidgets.horizontalSpace(AppTheme.doubleSpacing),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Next Injection Site:',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: AppColors.tertiary,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  'Site ${nextSite.siteNumber} in $bodyAreaText',
                  style: AppTextStyles.titleMedium,
                ),
              ],
            ),
          ),
          SharedWidgets.horizontalSpace(),
          Text(
            '${injectionDetails.siteRotation!.sites.length} sites',
            style: TextStyle(
              color: AppColors.onSurfaceVariant,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }
}
