// ABOUTME: Blood pressure chart screen for visualizing BP data over time
// ABOUTME: Interactive dual-line chart with medical categorization and trend analysis

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:albi/bloc/health_data_bloc.dart';
import 'package:albi/services/chart_data_service.dart';
import 'package:albi/utils/blood_pressure_utils.dart';
import 'package:albi/widgets/charts/bp_chart.dart';
import 'package:albi/widgets/charts/chart_date_selector.dart';

/// Screen for displaying blood pressure data visualization
class BloodPressureChartScreen extends StatefulWidget {
  const BloodPressureChartScreen({super.key});

  @override
  State<BloodPressureChartScreen> createState() => _BloodPressureChartScreenState();
}

class _BloodPressureChartScreenState extends State<BloodPressureChartScreen>
    with SingleTickerProviderStateMixin {
  final ChartDataService _chartDataService = ChartDataService();
  
  ChartTimePeriod _selectedPeriod = ChartTimePeriod.oneMonth;
  DateTimeRange? _customRange;
  bool _showCategoryZones = true;
  
  List<BPChartDataPoint>? _chartData;
  BPChartDataPoint? _selectedDataPoint;
  bool _isLoading = true;
  String? _error;
  
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _fadeAnimation = Tween<double>(begin: 0, end: 1).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );
    
    _loadChartData();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  /// Load blood pressure chart data
  Future<void> _loadChartData() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      final entries = await _chartDataService.getBloodPressureChartData(
        timePeriod: _selectedPeriod,
      );

      final chartData = entries.map((entry) => BPChartDataPoint(
        timestamp: entry.timestamp,
        systolic: entry.systolic,
        diastolic: entry.diastolic,
        notes: entry.notes,
        entryId: entry.id,
        category: entry.category,
      )).toList();

      setState(() {
        _chartData = chartData;
        _isLoading = false;
        _selectedDataPoint = null;
      });

      _animationController.forward();
    } catch (e) {
      setState(() {
        _error = 'Failed to load chart data: ${e.toString()}';
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Blood Pressure Chart'),
        backgroundColor: Theme.of(context).colorScheme.surface,
        foregroundColor: Theme.of(context).colorScheme.onSurface,
        actions: [
          IconButton(
            onPressed: _showChartSettings,
            icon: const Icon(Icons.settings),
            tooltip: 'Chart Settings',
          ),
          PopupMenuButton<String>(
            onSelected: _handleMenuSelection,
            itemBuilder: (context) => [
              PopupMenuItem(
                value: 'refresh',
                child: Row(
                  children: [
                    const Icon(Icons.refresh, size: 20),
                    const SizedBox(width: 8),
                    const Text('Refresh'),
                  ],
                ),
              ),
              PopupMenuItem(
                value: 'categories',
                child: Row(
                  children: [
                    Icon(
                      _showCategoryZones ? Icons.visibility : Icons.visibility_off,
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    Text(_showCategoryZones ? 'Hide Categories' : 'Show Categories'),
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
      body: _buildBody(),
    );
  }

  /// Build main body content
  Widget _buildBody() {
    return Column(
      children: [
        // Date range selector
        ChartDateSelector(
          selectedPeriod: _selectedPeriod,
          customRange: _customRange,
          onDateRangeSelected: _handleDateRangeChanged,
        ),
        
        // Main chart area
        Expanded(
          child: _buildChartArea(),
        ),
      ],
    );
  }

  /// Build the main chart area with loading/error states
  Widget _buildChartArea() {
    if (_isLoading) {
      return _buildLoadingState();
    }
    
    if (_error != null) {
      return _buildErrorState();
    }
    
    if (_chartData == null || _chartData!.isEmpty) {
      return _buildEmptyState();
    }

    return FadeTransition(
      opacity: _fadeAnimation,
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            // Chart legend with statistics
            _buildLegendCard(),
            
            const SizedBox(height: 16),
            
            // Main blood pressure chart
            Card(
              child: BPChart(
                data: _chartData!,
                showCategoryZones: _showCategoryZones,
                onDataPointTapped: _handleDataPointTapped,
              ),
            ),
            
            // Selected data point details
            if (_selectedDataPoint != null) ...[
              const SizedBox(height: 16),
              _buildDataPointDetails(),
            ],
            
            const SizedBox(height: 16),
            
            // Medical information card
            _buildMedicalInfoCard(),
          ],
        ),
      ),
    );
  }

  /// Build legend card with BP information
  Widget _buildLegendCard() {
    if (_chartData == null || _chartData!.isEmpty) return const SizedBox.shrink();

    final systolicValues = _chartData!.map((p) => p.systolic).toList();
    final diastolicValues = _chartData!.map((p) => p.diastolic).toList();
    
    final avgSystolic = systolicValues.reduce((a, b) => a + b) / systolicValues.length;
    final avgDiastolic = diastolicValues.reduce((a, b) => a + b) / diastolicValues.length;
    
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Blood Pressure Overview',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.w600,
              ),
            ),
            const SizedBox(height: 12),
            Row(
              children: [
                Expanded(
                  child: _buildStatItem(
                    'Readings',
                    _chartData!.length.toString(),
                    Icons.data_usage,
                    Colors.blue,
                  ),
                ),
                Expanded(
                  child: _buildStatItem(
                    'Avg Systolic',
                    '${avgSystolic.round()} mmHg',
                    Icons.trending_up,
                    Colors.red,
                  ),
                ),
                Expanded(
                  child: _buildStatItem(
                    'Avg Diastolic',
                    '${avgDiastolic.round()} mmHg',
                    Icons.trending_down,
                    Colors.blue,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// Build statistic item widget
  Widget _buildStatItem(String label, String value, IconData icon, Color color) {
    return Column(
      children: [
        Icon(icon, size: 20, color: color.withOpacity(0.7)),
        const SizedBox(height: 4),
        Text(
          value,
          style: Theme.of(context).textTheme.titleSmall?.copyWith(
            fontWeight: FontWeight.w600,
          ),
        ),
        Text(
          label,
          style: Theme.of(context).textTheme.bodySmall?.copyWith(
            color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
          ),
        ),
      ],
    );
  }

  /// Build selected data point details
  Widget _buildDataPointDetails() {
    final point = _selectedDataPoint!;
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Text(
                  'Selected Reading',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.w600,
                  ),
                ),
                const Spacer(),
                IconButton(
                  onPressed: () => setState(() => _selectedDataPoint = null),
                  icon: const Icon(Icons.close),
                  iconSize: 20,
                ),
              ],
            ),
            const SizedBox(height: 12),
            Row(
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '${point.systolic}/${point.diastolic} mmHg',
                        style: Theme.of(context).textTheme.titleLarge?.copyWith(
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        point.category.replaceAll('_', ' ').toUpperCase(),
                        style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                          color: Color(BloodPressureUtils.getCategoryColor(point.category).value),
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ],
                  ),
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                      'Pulse Pressure',
                      style: Theme.of(context).textTheme.bodySmall,
                    ),
                    Text(
                      '${point.pulsePressure} mmHg',
                      style: Theme.of(context).textTheme.titleSmall?.copyWith(
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      'MAP: ${point.meanArterialPressure.round()} mmHg',
                      style: Theme.of(context).textTheme.bodySmall,
                    ),
                  ],
                ),
              ],
            ),
            if (point.notes != null && point.notes!.isNotEmpty) ...[
              const SizedBox(height: 12),
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.3),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Text(
                  point.notes!,
                  style: Theme.of(context).textTheme.bodyMedium,
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  /// Build medical information card
  Widget _buildMedicalInfoCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.medical_information,
                  color: Theme.of(context).colorScheme.primary,
                  size: 20,
                ),
                const SizedBox(width: 8),
                Text(
                  'Blood Pressure Categories',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            _buildCategoryItem('Normal', 'Less than 120/80', Colors.green),
            _buildCategoryItem('Elevated', '120-129 systolic, less than 80 diastolic', Colors.orange),
            _buildCategoryItem('High Stage 1', '130-139/80-89', Colors.orange),
            _buildCategoryItem('High Stage 2', '140/90 or higher', Colors.red),
            _buildCategoryItem('Hypertensive Crisis', '180/120 or higher', Colors.purple),
          ],
        ),
      ),
    );
  }

  /// Build blood pressure category item
  Widget _buildCategoryItem(String category, String range, Color color) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        children: [
          Container(
            width: 12,
            height: 12,
            decoration: BoxDecoration(
              color: color,
              shape: BoxShape.circle,
            ),
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              category,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              range,
              style: Theme.of(context).textTheme.bodySmall?.copyWith(
                color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Build loading state
  Widget _buildLoadingState() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(),
          SizedBox(height: 16),
          Text('Loading blood pressure data...'),
        ],
      ),
    );
  }

  /// Build error state
  Widget _buildErrorState() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.error_outline,
              size: 64,
              color: Theme.of(context).colorScheme.error,
            ),
            const SizedBox(height: 16),
            Text(
              'Failed to load chart',
              style: Theme.of(context).textTheme.titleLarge?.copyWith(
                color: Theme.of(context).colorScheme.error,
              ),
            ),
            const SizedBox(height: 8),
            Text(
              _error!,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 24),
            ElevatedButton.icon(
              onPressed: _loadChartData,
              icon: const Icon(Icons.refresh),
              label: const Text('Retry'),
            ),
          ],
        ),
      ),
    );
  }

  /// Build empty state
  Widget _buildEmptyState() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.favorite,
              size: 64,
              color: Theme.of(context).colorScheme.primary.withOpacity(0.3),
            ),
            const SizedBox(height: 16),
            Text(
              'No blood pressure data',
              style: Theme.of(context).textTheme.titleLarge?.copyWith(
                color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
              ),
            ),
            const SizedBox(height: 8),
            Text(
              'Add blood pressure readings to see your health trends',
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Theme.of(context).colorScheme.onSurface.withOpacity(0.6),
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 24),
            ElevatedButton.icon(
              onPressed: () => Navigator.of(context).pop(),
              icon: const Icon(Icons.add),
              label: const Text('Add BP Reading'),
            ),
          ],
        ),
      ),
    );
  }

  /// Handle date range selection changes
  void _handleDateRangeChanged(ChartTimePeriod? timePeriod, DateTimeRange? customRange) {
    setState(() {
      if (customRange != null) {
        _customRange = customRange;
        _selectedPeriod = ChartTimePeriod.oneMonth; // Reset to default
      } else {
        _customRange = null;
        _selectedPeriod = timePeriod ?? ChartTimePeriod.oneMonth;
      }
    });
    _loadChartData();
  }

  /// Handle data point selection
  void _handleDataPointTapped(BPChartDataPoint? dataPoint) {
    setState(() {
      _selectedDataPoint = dataPoint;
    });
  }

  /// Handle menu selections
  void _handleMenuSelection(String value) {
    switch (value) {
      case 'refresh':
        _loadChartData();
        break;
      case 'categories':
        setState(() {
          _showCategoryZones = !_showCategoryZones;
        });
        break;
    }
  }

  /// Show chart settings dialog
  void _showChartSettings() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Chart Settings'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SwitchListTile(
              title: const Text('Show Category Zones'),
              subtitle: const Text('Display BP category reference lines'),
              value: _showCategoryZones,
              onChanged: (value) {
                setState(() => _showCategoryZones = value);
                Navigator.of(context).pop();
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Close'),
          ),
        ],
      ),
    );
  }
}
