// ABOUTME: Progress indicator widget for tracking export and import operations
// ABOUTME: Shows detailed progress with current operation, percentage, and step descriptions
import 'package:flutter/material.dart';

/// Progress indicator for backup operations
class BackupProgressIndicator extends StatelessWidget {
  final String title;
  final String? currentStep;
  final double? progress;
  final int? currentIndex;
  final int? totalSteps;
  final bool showCancel;
  final VoidCallback? onCancel;

  const BackupProgressIndicator({
    super.key,
    required this.title,
    this.currentStep,
    this.progress,
    this.currentIndex,
    this.totalSteps,
    this.showCancel = true,
    this.onCancel,
  });

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(title),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (currentStep != null) ...[
            Text(
              currentStep!,
              style: Theme.of(context).textTheme.bodyMedium,
            ),
            const SizedBox(height: 16),
          ],
          
          // Progress bar
          if (progress != null)
            LinearProgressIndicator(value: progress)
          else
            const LinearProgressIndicator(),
          
          const SizedBox(height: 12),
          
          // Step counter
          if (currentIndex != null && totalSteps != null)
            Text(
              'Step $currentIndex of $totalSteps',
              style: Theme.of(context).textTheme.bodySmall,
            )
          else if (progress != null)
            Text(
              '${(progress! * 100).toInt()}% complete',
              style: Theme.of(context).textTheme.bodySmall,
            ),
        ],
      ),
      actions: [
        if (showCancel)
          TextButton(
            onPressed: onCancel,
            child: const Text('Cancel'),
          ),
      ],
    );
  }
}

/// Show progress dialog for backup operations
Future<T?> showBackupProgress<T>({
  required BuildContext context,
  required String title,
  required Future<T> operation,
  Stream<String>? stepUpdates,
  Stream<double>? progressUpdates,
  bool barrierDismissible = false,
}) async {
  String? currentStep;
  double? progress;
  
  return showDialog<T>(
    context: context,
    barrierDismissible: barrierDismissible,
    builder: (context) {
      return StatefulBuilder(
        builder: (context, setState) {
          // Listen to step updates
          stepUpdates?.listen((step) {
            if (context.mounted) {
              setState(() {
                currentStep = step;
              });
            }
          });
          
          // Listen to progress updates
          progressUpdates?.listen((prog) {
            if (context.mounted) {
              setState(() {
                progress = prog;
              });
            }
          });
          
          return BackupProgressIndicator(
            title: title,
            currentStep: currentStep,
            progress: progress,
            onCancel: () => Navigator.of(context).pop(),
          );
        },
      );
    },
  ).then((result) {
    // Execute the operation and handle result
    operation.then((operationResult) {
      if (context.mounted) {
        Navigator.of(context).pop(operationResult);
      }
    }).catchError((error) {
      if (context.mounted) {
        Navigator.of(context).pop();
        // Show error dialog
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('Operation Failed'),
            content: Text(error.toString()),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('OK'),
              ),
            ],
          ),
        );
      }
    });
    
    return result;
  });
}

/// Progress indicator for tracking multiple steps
class StepProgressIndicator extends StatelessWidget {
  final List<String> steps;
  final int currentStepIndex;
  final bool isComplete;
  final String? errorMessage;

  const StepProgressIndicator({
    super.key,
    required this.steps,
    required this.currentStepIndex,
    this.isComplete = false,
    this.errorMessage,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        for (int i = 0; i < steps.length; i++)
          _buildStepRow(
            context,
            steps[i],
            i,
            _getStepStatus(i),
          ),
        
        if (errorMessage != null) ...[
          const SizedBox(height: 16),
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.errorContainer,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              children: [
                Icon(
                  Icons.error,
                  color: Theme.of(context).colorScheme.error,
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    errorMessage!,
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.onErrorContainer,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ],
    );
  }

  Widget _buildStepRow(BuildContext context, String step, int index, StepStatus status) {
    late IconData icon;
    late Color color;
    
    switch (status) {
      case StepStatus.pending:
        icon = Icons.radio_button_unchecked;
        color = Theme.of(context).colorScheme.outline;
        break;
      case StepStatus.inProgress:
        icon = Icons.hourglass_empty;
        color = Theme.of(context).colorScheme.primary;
        break;
      case StepStatus.completed:
        icon = Icons.check_circle;
        color = Theme.of(context).colorScheme.primary;
        break;
      case StepStatus.error:
        icon = Icons.error;
        color = Theme.of(context).colorScheme.error;
        break;
    }
    
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        children: [
          Icon(icon, color: color, size: 20),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              step,
              style: TextStyle(
                color: status == StepStatus.pending 
                  ? Theme.of(context).colorScheme.outline
                  : null,
                fontWeight: status == StepStatus.inProgress 
                  ? FontWeight.w500 
                  : null,
              ),
            ),
          ),
        ],
      ),
    );
  }

  StepStatus _getStepStatus(int index) {
    if (errorMessage != null && index == currentStepIndex) {
      return StepStatus.error;
    }
    
    if (index < currentStepIndex || isComplete) {
      return StepStatus.completed;
    } else if (index == currentStepIndex && !isComplete) {
      return StepStatus.inProgress;
    } else {
      return StepStatus.pending;
    }
  }
}

enum StepStatus {
  pending,
  inProgress,
  completed,
  error,
}
