import 'package:flutter/material.dart';
import '../models/models.dart';
import '../risk_engine/calculator.dart';
import '../storage/local_storage.dart';
import '../theme.dart';
import 'about_screen.dart';
import 'baseline_screen.dart';
import 'onboarding_screen.dart';
import 'saved_runs_screen.dart';

class ResultsScreen extends StatefulWidget {
  final UserProfile profile;
  final BehavioralInputs behaviors;

  const ResultsScreen({
    super.key,
    required this.profile,
    required this.behaviors,
  });

  @override
  State<ResultsScreen> createState() => _ResultsScreenState();
}

class _ResultsScreenState extends State<ResultsScreen> {
  late CalculationResult _result;

  @override
  void initState() {
    super.initState();
    _result = calculateRankedFactors(widget.profile, widget.behaviors);
    _saveResult();
  }

  Future<void> _saveResult() async {
    await LocalStorage.saveResult(_result);
  }

  @override
  Widget build(BuildContext context) {
    final dominant = _result.dominantFactor;
    final secondary = _result.secondaryFactor;

    return Scaffold(
      appBar: AppBar(
        title: const Text('Results'),
        automaticallyImplyLeading: false,
        actions: [
          IconButton(
            icon: const Icon(Icons.info_outline),
            onPressed: () => Navigator.push(
              context,
              MaterialPageRoute(builder: (_) => const AboutScreen()),
            ),
          ),
        ],
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(24),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (dominant != null) ...[
                // Dominant challenge card
                _buildDominantCard(dominant),
                const SizedBox(height: 24),

                // Explanation
                Text(
                  'Addressing this exposure would likely produce the largest increase in expected lifespan among available changes.',
                  style: Theme.of(context).textTheme.bodyMedium,
                ),
                const SizedBox(height: 32),

                // Secondary factor
                if (secondary != null) ...[
                  Text(
                    'Secondary Factor',
                    style: Theme.of(context).textTheme.headlineSmall,
                  ),
                  const SizedBox(height: 12),
                  _buildSecondaryCard(secondary),
                  const SizedBox(height: 32),
                ],

                // All factors
                if (_result.rankedFactors.length > 2) ...[
                  Text(
                    'All Factors',
                    style: Theme.of(context).textTheme.headlineSmall,
                  ),
                  const SizedBox(height: 12),
                  ..._result.rankedFactors.skip(2).map((factor) {
                    return Padding(
                      padding: const EdgeInsets.only(bottom: 8),
                      child: _buildFactorRow(factor),
                    );
                  }),
                  const SizedBox(height: 24),
                ],
              ] else ...[
                // No factors to improve
                _buildOptimalCard(),
                const SizedBox(height: 24),
              ],

              // Model version
              Center(
                child: Text(
                  'Model v${_result.modelVersion}',
                  style: Theme.of(context).textTheme.bodySmall,
                ),
              ),
              const SizedBox(height: 32),

              // Action buttons
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _saveRun,
                  child: const Text('Save Run'),
                ),
              ),
              const SizedBox(height: 12),
              SizedBox(
                width: double.infinity,
                child: OutlinedButton(
                  onPressed: _recalculate,
                  child: const Text('Recalculate'),
                ),
              ),
              const SizedBox(height: 12),
              Center(
                child: TextButton(
                  onPressed: _viewSavedRuns,
                  child: const Text('View Saved Runs'),
                ),
              ),
              const SizedBox(height: 24),
              SizedBox(
                width: double.infinity,
                child: OutlinedButton(
                  onPressed: _showDeleteConfirmation,
                  style: OutlinedButton.styleFrom(
                    foregroundColor: AppColors.error,
                    side: const BorderSide(color: AppColors.error),
                  ),
                  child: const Text('Delete All Data'),
                ),
              ),
              const SizedBox(height: 16),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildDominantCard(RankedFactor factor) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [AppColors.primary, AppColors.primaryDark],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        borderRadius: BorderRadius.circular(20),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            'DOMINANT CHALLENGE',
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w700,
              color: Colors.white70,
              letterSpacing: 1.2,
            ),
          ),
          const SizedBox(height: 12),
          Text(
            factor.displayName,
            style: const TextStyle(
              fontSize: 28,
              fontWeight: FontWeight.w700,
              color: Colors.white,
              letterSpacing: -0.5,
            ),
          ),
          const SizedBox(height: 20),
          Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      'ESTIMATED GAIN',
                      style: TextStyle(
                        fontSize: 11,
                        fontWeight: FontWeight.w600,
                        color: Colors.white60,
                        letterSpacing: 0.8,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      '${factor.delta.rangeDisplay} months',
                      style: const TextStyle(
                        fontSize: 24,
                        fontWeight: FontWeight.w700,
                        color: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: Colors.white.withAlpha(51),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Text(
                  _getConfidenceLabel(factor.delta.confidence),
                  style: const TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildSecondaryCard(RankedFactor factor) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: AppColors.surface,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: AppColors.divider),
      ),
      child: Row(
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  factor.displayName,
                  style: Theme.of(context).textTheme.headlineSmall,
                ),
                const SizedBox(height: 4),
                Text(
                  '${factor.delta.rangeDisplay} months',
                  style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                        color: AppColors.primary,
                        fontWeight: FontWeight.w600,
                      ),
                ),
              ],
            ),
          ),
          _buildConfidenceBadge(factor.delta.confidence),
        ],
      ),
    );
  }

  Widget _buildFactorRow(RankedFactor factor) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: AppColors.surfaceVariant,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            factor.displayName,
            style: Theme.of(context).textTheme.bodyLarge,
          ),
          Text(
            '${factor.delta.rangeDisplay} mo',
            style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                  color: AppColors.primary,
                  fontWeight: FontWeight.w600,
                ),
          ),
        ],
      ),
    );
  }

  Widget _buildOptimalCard() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: AppColors.success.withAlpha(26),
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: AppColors.success.withAlpha(77)),
      ),
      child: Column(
        children: [
          const Icon(
            Icons.check_circle_outline,
            size: 48,
            color: AppColors.success,
          ),
          const SizedBox(height: 16),
          Text(
            'No significant factors identified',
            style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                  color: AppColors.success,
                ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 8),
          Text(
            'Your current behaviors are near optimal based on our model.',
            style: Theme.of(context).textTheme.bodyMedium,
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildConfidenceBadge(Confidence confidence) {
    Color color;
    switch (confidence) {
      case Confidence.high:
        color = AppColors.success;
        break;
      case Confidence.moderate:
        color = AppColors.warning;
        break;
      case Confidence.emerging:
        color = AppColors.textTertiary;
        break;
    }

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
      decoration: BoxDecoration(
        color: color.withAlpha(26),
        borderRadius: BorderRadius.circular(6),
      ),
      child: Text(
        _getConfidenceLabel(confidence),
        style: TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.w600,
          color: color,
        ),
      ),
    );
  }

  String _getConfidenceLabel(Confidence confidence) {
    switch (confidence) {
      case Confidence.high:
        return 'High';
      case Confidence.moderate:
        return 'Moderate';
      case Confidence.emerging:
        return 'Emerging';
    }
  }

  void _recalculate() {
    Navigator.of(context).pushAndRemoveUntil(
      MaterialPageRoute(builder: (_) => const BaselineScreen()),
      (route) => false,
    );
  }

  void _showDeleteConfirmation() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Delete All Data'),
        content: const Text(
          'This will permanently delete all your data from this device. This action cannot be undone.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () async {
              final navigator = Navigator.of(context);
              await LocalStorage.deleteAllData();
              navigator.pushAndRemoveUntil(
                MaterialPageRoute(builder: (_) => const OnboardingScreen()),
                (route) => false,
              );
            },
            style: TextButton.styleFrom(foregroundColor: AppColors.error),
            child: const Text('Delete'),
          ),
        ],
      ),
    );
  }

  void _saveRun() {
    final controller = TextEditingController();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Save Run'),
        content: TextField(
          controller: controller,
          autofocus: true,
          decoration: const InputDecoration(
            hintText: 'Enter a label for this run',
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () async {
              final label = controller.text.trim();
              if (label.isNotEmpty) {
                final navigator = Navigator.of(context);
                final messenger = ScaffoldMessenger.of(context);
                await LocalStorage.saveSavedRun(
                  label: label,
                  result: _result,
                  profile: widget.profile,
                  behaviors: widget.behaviors,
                );
                navigator.pop();
                messenger.showSnackBar(
                  const SnackBar(content: Text('Run saved')),
                );
              }
            },
            child: const Text('Save'),
          ),
        ],
      ),
    );
  }

  void _viewSavedRuns() {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (_) => const SavedRunsScreen()),
    );
  }
}
