// ABOUTME: Import dialog widget for configuring backup import with conflict resolution and validation
// ABOUTME: Shows backup file preview, allows conflict resolution selection, and handles import confirmation
import 'package:flutter/material.dart';
import '../../models/backup/backup_metadata.dart';
import '../../models/backup/import_result.dart';

/// Dialog for configuring import options and showing backup preview
class ImportDialog extends StatefulWidget {
  final BackupMetadata? metadata;
  final ConflictResolution initialConflictResolution;
  final bool includeSettings;
  final VoidCallback? onImport;

  const ImportDialog({
    super.key,
    this.metadata,
    this.initialConflictResolution = ConflictResolution.keepExisting,
    this.includeSettings = false,
    this.onImport,
  });

  @override
  State<ImportDialog> createState() => _ImportDialogState();
}

class _ImportDialogState extends State<ImportDialog> {
  late ConflictResolution _conflictResolution;
  late bool _includeSettings;

  @override
  void initState() {
    super.initState();
    _conflictResolution = widget.initialConflictResolution;
    _includeSettings = widget.includeSettings;
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('Import Backup'),
      content: SizedBox(
        width: double.maxFinite,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (widget.metadata != null) ...[
              _buildBackupInfo(),
              const SizedBox(height: 24),
            ],
            
            Text(
              'Import options:',
              style: Theme.of(context).textTheme.titleSmall,
            ),
            const SizedBox(height: 16),
            
            // Conflict resolution
            _buildConflictResolution(),
            
            const SizedBox(height: 16),
            
            // Settings import option
            if (widget.metadata?.hasSettings == true)
              _buildSettingsOption(),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('Cancel'),
        ),
        FilledButton(
          onPressed: () {
            Navigator.of(context).pop({
              'conflictResolution': _conflictResolution,
              'includeSettings': _includeSettings,
            });
            widget.onImport?.call();
          },
          child: const Text('Import'),
        ),
      ],
    );
  }

  Widget _buildBackupInfo() {
    final metadata = widget.metadata!;
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Backup Information',
              style: Theme.of(context).textTheme.titleMedium,
            ),
            const SizedBox(height: 12),
            _buildInfoRow('Created', _formatDate(metadata.createdAt)),
            _buildInfoRow('App Version', metadata.appVersion),
            if (metadata.deviceInfo.isNotEmpty)
              _buildInfoRow('Device', metadata.deviceInfo['platform']?.toString() ?? 'Unknown'),
            const SizedBox(height: 8),
            Text(
              'Data Contents:',
              style: Theme.of(context).textTheme.titleSmall,
            ),
            const SizedBox(height: 4),
            if (metadata.dataTypeCounts['weight'] != null)
              _buildInfoRow('Weight entries', '${metadata.dataTypeCounts['weight']}'),
            if (metadata.dataTypeCounts['bloodPressure'] != null)
              _buildInfoRow('Blood pressure entries', '${metadata.dataTypeCounts['bloodPressure']}'),
            if (metadata.dataTypeCounts['mood'] != null)
              _buildInfoRow('Mood entries', '${metadata.dataTypeCounts['mood']}'),
          ],
        ),
      ),
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(label, style: const TextStyle(fontWeight: FontWeight.w500)),
          Text(value),
        ],
      ),
    );
  }

  Widget _buildConflictResolution() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          'When data conflicts occur:',
          style: Theme.of(context).textTheme.titleSmall,
        ),
        const SizedBox(height: 8),
        RadioListTile<ConflictResolution>(
          title: const Text('Keep existing data'),
          subtitle: const Text('Skip importing duplicate entries'),
          value: ConflictResolution.keepExisting,
          groupValue: _conflictResolution,
          onChanged: (value) {
            setState(() {
              _conflictResolution = value!;
            });
          },
        ),
        RadioListTile<ConflictResolution>(
          title: const Text('Replace with imported'),
          subtitle: const Text('Overwrite existing entries with backup data'),
          value: ConflictResolution.replaceWithImported,
          groupValue: _conflictResolution,
          onChanged: (value) {
            setState(() {
              _conflictResolution = value!;
            });
          },
        ),
        RadioListTile<ConflictResolution>(
          title: const Text('Merge by timestamp'),
          subtitle: const Text('Keep the most recent version of each entry'),
          value: ConflictResolution.mergeByTimestamp,
          groupValue: _conflictResolution,
          onChanged: (value) {
            setState(() {
              _conflictResolution = value!;
            });
          },
        ),
      ],
    );
  }

  Widget _buildSettingsOption() {
    return SwitchListTile(
      title: const Text('Import App Settings'),
      subtitle: const Text('Replace current app preferences'),
      value: _includeSettings,
      onChanged: (value) {
        setState(() {
          _includeSettings = value;
        });
      },
    );
  }

  String _formatDate(DateTime date) {
    return '${date.day}/${date.month}/${date.year} at ${date.hour}:${date.minute.toString().padLeft(2, '0')}';
  }
}

/// Show import dialog with backup preview and return import options
Future<Map<String, dynamic>?> showImportDialog({
  required BuildContext context,
  BackupMetadata? metadata,
  ConflictResolution initialConflictResolution = ConflictResolution.keepExisting,
  bool includeSettings = false,
  VoidCallback? onImport,
}) async {
  return showDialog<Map<String, dynamic>>(
    context: context,
    builder: (context) => ImportDialog(
      metadata: metadata,
      initialConflictResolution: initialConflictResolution,
      includeSettings: includeSettings,
      onImport: onImport,
    ),
  );
}
