// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
// dialog_service.dart
import 'package:intl/intl.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:nokken/src/core/services/navigation/navigation_service.dart';
import 'package:nokken/src/core/ui/theme/app_colors.dart';
import 'package:nokken/src/core/ui/theme/app_text_styles.dart';

class DialogService {
  /// Shows a dialog asking user if they want to save unsaved changes
  /// Returns true if user chooses to save, false if they choose to discard
  static Future<void> showSaveChangesDialog({
    required BuildContext context,
    required WidgetRef ref,
    required Future<void> Function() onSave,
    VoidCallback? onDiscard,
  }) async {
    final result = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Unsaved Changes'),
        content: const Text(
            'You have unsaved changes. Would you like to save them?'),
        actions: [
          TextButton(
            onPressed: () => NavigationService.goBackWithResult(context, false),
            style: TextButton.styleFrom(
              foregroundColor: AppColors.error,
            ),
            child: const Text('Discard'),
          ),
          TextButton(
            onPressed: () => NavigationService.goBackWithResult(context, true),
            child: Text(
              'Save',
              style: AppTextStyles.titleMedium,
            ),
          ),
        ],
      ),
    );

    if (!context.mounted) return;

    if (result == true) {
      await onSave();
    } else if (context.mounted) {
      if (onDiscard != null) {
        onDiscard();
      } else {
        NavigationService.goBack(context);
      }
    }
  }

  /// Shows a delete confirmation dialog
  /// Returns true if user confirms deletion, false otherwise
  static Future<void> showDeleteDialog({
    required BuildContext context,
    required WidgetRef ref,
    required String itemName,
    required Future<void> Function() onDelete,
  }) async {
    final result = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Delete Item'),
        content: Text('Are you sure you want to delete $itemName?'),
        actions: [
          TextButton(
            onPressed: () => NavigationService.goBackWithResult(context, false),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () => NavigationService.goBackWithResult(context, true),
            style: TextButton.styleFrom(
              foregroundColor: AppColors.error,
            ),
            child: const Text('Delete'),
          ),
        ],
      ),
    );

    if (result == true && context.mounted) {
      await onDelete();
    }
  }

  /// Shows a dialog with bloodwork details and options to close or edit
  static Future<void> showBloodworkDetailDialog({
    required BuildContext context,
    required String hormoneType,
    required DateTime date,
    required double value,
    required String unit,
    required dynamic record,
  }) async {
    await showDialog(
      context: context,
      builder: (dialogContext) => AlertDialog(
        title: Text(hormoneType),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Date: ${DateFormat('MM/dd/yyyy').format(date)}'),
            Text('Value: ${value.toStringAsFixed(1)} $unit'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(dialogContext),
            child: Text(
              'Close',
              style: AppTextStyles.labelMedium.copyWith(
                color: AppColors.primary,
                backgroundColor: AppColors.primary.withAlpha(20),
              ),
            ),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(dialogContext);
              NavigationService.goToBloodworkAddEdit(
                context,
                bloodwork: record,
              );
            },
            child: Text(
              'Edit',
              style: AppTextStyles.labelMedium.copyWith(
                color: AppColors.primary,
                backgroundColor: AppColors.primary.withAlpha(20),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Generic back button handler that checks for unsaved changes
  static void handleBackWithUnsavedChanges({
    required BuildContext context,
    required WidgetRef ref,
    required bool Function() checkForUnsavedChanges,
    required Future<void> Function() saveFn,
  }) async {
    // Check if there are unsaved changes
    bool hasUnsavedChanges = checkForUnsavedChanges();

    if (hasUnsavedChanges) {
      await showSaveChangesDialog(
        context: context,
        ref: ref,
        onSave: saveFn,
      );
    } else {
      // No unsaved changes, just go back
      NavigationService.goBack(context);
    }
  }
}
