// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
//  medication_detail_screen.dart
//  Screen that displays more detailed information about a medication
//
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:nokken/src/core/ui/theme/app_icons.dart';
import 'package:nokken/src/features/medication_tracker/models/medication.dart';
import 'package:nokken/src/core/services/navigation/navigation_service.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/utils/get_icons_colors.dart';
import 'package:nokken/src/core/utils/get_labels.dart';
import 'package:nokken/src/core/utils/date_time_formatter.dart';

class MedicationDetailScreen extends ConsumerWidget {
  final Medication medication;

  const MedicationDetailScreen({
    super.key,
    required this.medication,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Scaffold(
      appBar: AppBar(
        title: Text(medication.name),
        leading: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            IconButton(
              icon: Icon(AppIcons.getIcon('arrow_back')),
              onPressed: () => NavigationService.goHome(context),
            ),
          ],
        ),
        actions: [
          // Edit button
          TextButton(
            onPressed: () => NavigationService.goToMedicationAddEdit(context,
                medication: medication),
            child: Text(
              'Edit',
              style: AppTextStyles.titleMedium,
            ),
          ),
        ],
      ),
      body: ListView(
        padding: AppTheme.standardCardPadding,
        children: [
          // Refill alert banner
          if (medication.needsRefill())
            Card(
              color: AppColors.errorContainer,
              child: Padding(
                padding: AppTheme.standardCardPadding,
                child: Row(
                  children: [
                    Icon(
                      AppIcons.getIcon('warning'),
                      color: AppColors.error,
                    ),
                    SharedWidgets.verticalSpace(),
                    Text(
                      'Refill needed',
                      style: AppTextStyles.error,
                    ),
                  ],
                ),
              ),
            ),

          // Basic medication information card
          Card(
            child: Padding(
              padding: AppTheme.standardCardPadding,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      GetIconsColors.getMedicationIconCirlce(
                          medication.medicationType),
                      SharedWidgets.horizontalSpace(),
                      Expanded(
                        child: Text(
                          medication.name,
                          style: AppTextStyles.titleLarge,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                  SharedWidgets.verticalSpace(AppTheme.cardPadding),
                  SharedWidgets.buildInfoRow('Dosage', medication.dosage),
                  SharedWidgets.verticalSpace(),
                  SharedWidgets.buildInfoRow(
                      'Type', GetLabels.getMedicationTypeText(medication)),
                  SharedWidgets.verticalSpace(),
                  SharedWidgets.buildInfoRow('Frequency',
                      DateTimeFormatter.formatMedicationFrequency(medication)),
                  SharedWidgets.verticalSpace(),
                  if (medication.currentQuantity > 0 ||
                      medication.refillThreshold > 0)
                    SharedWidgets.buildInfoRow('Remaining / Refill',
                        '${medication.currentQuantity} / ${medication.refillThreshold}'),
                ],
              ),
            ),
          ),
          SharedWidgets.verticalSpace(AppTheme.cardSpacing),

          // Healthcare Providers card (if either doctor or pharmacy is provided)
          if (medication.doctor != null || medication.pharmacy != null) ...[
            SharedWidgets.basicCard(
              context: context,
              title: 'Healthcare Providers',
              children: [
                if (medication.doctor != null)
                  SharedWidgets.buildInfoRow('Doctor', medication.doctor!),
                if (medication.doctor != null && medication.pharmacy != null)
                  SharedWidgets.verticalSpace(),
                if (medication.pharmacy != null)
                  SharedWidgets.buildInfoRow('Pharmacy', medication.pharmacy!),
              ],
            ),
            SharedWidgets.verticalSpace(AppTheme.cardSpacing),
          ],

          // Schedule information card
          SharedWidgets.basicCard(
            context: context,
            title: medication.medicationType == MedicationType.patch
                ? 'Change Schedule'
                : 'Schedule',
            children: [
              // Display schedule type
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  medication.asNeeded
                      ? Icon(Icons.event_available)
                      : Icon(AppIcons.getIcon('calendar')),
                  SharedWidgets.horizontalSpace(),
                  Expanded(
                    child: Text(
                        medication.asNeeded
                            ? 'Take as needed'
                            : DateTimeFormatter.formatDaysOfWeek(
                                medication.daysOfWeek),
                        style: AppTextStyles.bodyLarge),
                  ),
                ],
              ),

              // Only show time slots for scheduled medications (not as-needed)
              if (!medication.asNeeded) ...[
                SharedWidgets.verticalSpace(AppTheme.spacing * 2),

                // Sort and display all time slots chronologically
                ...(() {
                  // Create a sorted copy of all time slots
                  final sortedTimes = List<DateTime>.from(medication.timeOfDay);
                  sortedTimes.sort((a, b) {
                    final aTimeStr = DateTimeFormatter.formatTimeToAMPM(
                        TimeOfDay.fromDateTime(a));
                    final bTimeStr = DateTimeFormatter.formatTimeToAMPM(
                        TimeOfDay.fromDateTime(b));
                    return DateTimeFormatter.compareTimeSlots(
                        aTimeStr, bTimeStr);
                  });

                  // Convert each time slot to a UI element
                  return sortedTimes.map((time) {
                    final timeOfDay = TimeOfDay.fromDateTime(time);
                    final timeStr =
                        DateTimeFormatter.formatTimeToAMPM(timeOfDay);
                    return Padding(
                      padding: const EdgeInsets.only(bottom: 8),
                      child: Row(
                        children: [
                          Icon(DateTimeFormatter.getTimeIcon(timeStr)),
                          SharedWidgets.horizontalSpace(AppTheme.spacing),
                          Text(timeStr, style: AppTextStyles.bodyMedium),
                        ],
                      ),
                    );
                  }).toList();
                })(),
              ],
            ],
          ),
          SharedWidgets.verticalSpace(AppTheme.cardSpacing),

          // Injection details card - only shown for injection medications
          if (medication.medicationType == MedicationType.injection &&
              medication.injectionDetails != null) ...[
            SharedWidgets.basicCard(
              context: context,
              title: 'Injection Details',
              children: [
                SharedWidgets.buildInfoRow(
                    'Type',
                    GetLabels.getInjectionSubtypeText(
                        medication.injectionDetails!.subtype)),
                SharedWidgets.verticalSpace(AppTheme.spacing * 2),

                // Injection Site Rotation - NEW SECTION
                if (medication.injectionDetails!.siteRotation != null &&
                    medication
                        .injectionDetails!.siteRotation!.sites.isNotEmpty) ...[
                  Text('Next Injection Site', style: AppTextStyles.titleSmall),
                  SharedWidgets.verticalSpace(),
                  _buildNextInjectionSite(medication.injectionDetails!),
                  SharedWidgets.verticalSpace(AppTheme.spacing * 2),

                  // Button to advance to next site
                  /*   Align(
                    alignment: Alignment.centerRight,
                    child: TextButton.icon(
                      icon: Icon(AppIcons.getIcon('redo')),
                      label: const Text('Advance to next site'),
                      onPressed: () {
                        _advanceToNextSite(context, ref);
                      },
                    ),
                  ),*/

                  SharedWidgets.verticalSpace(),
                ] else if (medication.injectionDetails!.subtype !=
                    InjectionSubtype.intravenous) ...[
                  // Only show this for IM and SC injections (not IV)
                  Text('Injection Site Rotation',
                      style: AppTextStyles.titleSmall),
                  SharedWidgets.verticalSpace(),
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: AppColors.info.withAlpha(20),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Row(
                      children: [
                        Icon(AppIcons.getIcon('info'),
                            color: AppColors.info, size: 20),
                        SharedWidgets.horizontalSpace(),
                        const Expanded(
                          child: Text(
                            'No injection site rotation configured. Edit this medication to set up site rotation.',
                            style: TextStyle(fontStyle: FontStyle.italic),
                          ),
                        ),
                      ],
                    ),
                  ),
                  SharedWidgets.verticalSpace(AppTheme.spacing * 2),
                ],

// Syringes section
                if (medication.injectionDetails!.syringeType != '' ||
                    medication.injectionDetails!.syringeRefills > 0) ...[
                  Text('Syringes', style: AppTextStyles.titleMedium),
                  SharedWidgets.verticalSpace(),
                ],
                if (medication.injectionDetails!.syringeType != '') ...[
                  SharedWidgets.buildInfoRow(
                      'Type', medication.injectionDetails!.syringeType),
                  SharedWidgets.verticalSpace(),
                ],
                if (medication.injectionDetails!.syringeCount > 0 ||
                    medication.injectionDetails!.syringeRefills > 0) ...[
                  SharedWidgets.buildInfoRow('Remaining / Refill',
                      '${medication.injectionDetails!.syringeCount} / ${medication.injectionDetails!.syringeRefills.toString()}'),
                  SharedWidgets.verticalSpace(),
                ],

                // Drawing Needles section
                if (medication.injectionDetails!.drawingNeedleType != '' ||
                    medication.injectionDetails!.drawingNeedleRefills > 0) ...[
                  Text('Drawing Needles', style: AppTextStyles.titleMedium),
                  SharedWidgets.verticalSpace(),
                ],
                if (medication.injectionDetails!.drawingNeedleType != '') ...[
                  SharedWidgets.buildInfoRow(
                      'Type', medication.injectionDetails!.drawingNeedleType),
                  SharedWidgets.verticalSpace(),
                ],
                if (medication.injectionDetails!.drawingNeedleCount > 0 ||
                    medication.injectionDetails!.drawingNeedleRefills > 0) ...[
                  SharedWidgets.buildInfoRow('Remaining / Refill',
                      '${medication.injectionDetails!.drawingNeedleCount} / ${medication.injectionDetails!.drawingNeedleRefills.toString()}'),
                  SharedWidgets.verticalSpace(),
                ],

                // Injecting Needles section
                if (medication.injectionDetails!.injectingNeedleType != '' ||
                    medication.injectionDetails!.injectingNeedleRefills >
                        0) ...[
                  Text('Injecting Needles', style: AppTextStyles.titleMedium),
                  SharedWidgets.verticalSpace(),
                ],
                if (medication.injectionDetails!.injectingNeedleType != '') ...[
                  SharedWidgets.buildInfoRow(
                      'Type', medication.injectionDetails!.injectingNeedleType),
                  SharedWidgets.verticalSpace(),
                ],
                if (medication.injectionDetails!.injectingNeedleCount > 0 ||
                    medication.injectionDetails!.injectingNeedleRefills >
                        0) ...[
                  SharedWidgets.buildInfoRow('Remaining / Refill',
                      '${medication.injectionDetails!.injectingNeedleCount} / ${medication.injectionDetails!.injectingNeedleRefills.toString()}'),
                ],
                // Injection site notes
                /*             if (medication
                    .injectionDetails!.injectionSiteNotes.isNotEmpty) ...[
                  SharedWidgets.verticalSpace(AppTheme.spacing * 2),
                  Text('Injection Notes', style: AppTextStyles.titleSmall),
                  SharedWidgets.verticalSpace(),
                  Text(medication.injectionDetails!.injectionSiteNotes),
                ], 
     */
              ],
            ),
            SharedWidgets.verticalSpace(AppTheme.cardSpacing),
          ],

          // Notes card - only shown if notes exist
          if (medication.notes?.isNotEmpty == true) ...[
            SharedWidgets.verticalSpace(AppTheme.cardSpacing),
            SharedWidgets.basicCard(
              context: context,
              title: 'Notes',
              children: [
                Text(medication.notes!),
              ],
            ),
          ],
        ],
      ),
    );
  }

  /// Build a widget showing the next injection site information
  Widget _buildNextInjectionSite(InjectionDetails details) {
    if (details.siteRotation == null || details.siteRotation!.sites.isEmpty) {
      return const SizedBox.shrink();
    }

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

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: AppColors.tertiary.withAlpha(20),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: AppColors.tertiary),
      ),
      child: Row(
        children: [
          // Site number in circle
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: AppColors.tertiary,
            ),
            child: Center(
              child: Text(
                '${nextSite.siteNumber}',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: AppColors.onTertiary,
                ),
              ),
            ),
          ),
          SharedWidgets.horizontalSpace(AppTheme.doubleSpacing),
          // Body area text
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  bodyAreaText,
                  style: AppTextStyles.titleMedium,
                ),
                Text(
                  'Total sites: ${details.siteRotation!.sites.length}',
                  style: AppTextStyles.bodySmall,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
