// ABOUTME: Charts screen for data visualization of health tracking metrics
// ABOUTME: Provides navigation to different chart types and quick data overview
import 'package:flutter/material.dart';
import 'package:albi/screens/weight_chart_screen.dart';
import 'package:albi/screens/blood_pressure_chart_screen.dart';
import 'package:albi/screens/mood_chart_screen.dart';
import 'package:albi/services/chart_data_service.dart';
import 'package:albi/widgets/shared_app_bar.dart';
import 'package:albi/utils/constants.dart';

class ChartsScreen extends StatefulWidget {
  final VoidCallback? onThemeToggle;
  final bool isDarkMode;

  const ChartsScreen({
    super.key,
    this.onThemeToggle,
    required this.isDarkMode,
  });

  @override
  State<ChartsScreen> createState() => _ChartsScreenState();
}

class _ChartsScreenState extends State<ChartsScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: SharedAppBar(
        title: 'Charts',
        onThemeToggle: widget.onThemeToggle,
        isDarkMode: widget.isDarkMode,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Data Visualisation',
                      style: Theme.of(context).textTheme.headlineSmall?.copyWith(
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      'Visualise your health data with interactive charts',
                      style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                        color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
                      ),
                    ),
                    const SizedBox(height: 24),
                    
                    _ChartNavigationCard(
                      title: 'Weight Trends',
                      description: 'Track your weight changes over time with interactive charts',
                      icon: Icons.trending_up,
                      color: Colors.blue,
                      isAvailable: true,
                      onTap: () => _navigateToWeightChart(context),
                    ),
                    const SizedBox(height: 16),
                    
                    _ChartNavigationCard(
                      title: 'Blood Pressure Monitor',
                      description: 'Monitor systolic and diastolic readings with medical insights',
                      icon: Icons.favorite,
                      color: Colors.red,
                      isAvailable: true,
                      onTap: () => _navigateToBloodPressureChart(context),
                    ),
                    const SizedBox(height: 16),
                    
                    _ChartNavigationCard(
                      title: 'Mood Patterns',
                      description: 'Analyse your mood patterns and emotional trends',
                      icon: Icons.mood,
                      color: Colors.orange,
                      isAvailable: true,
                      onTap: () => _navigateToMoodChart(context),
                    ),
                    const SizedBox(height: 24),

                    _QuickStatsCard(),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Navigate to the weight chart screen
  void _navigateToWeightChart(BuildContext context) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const WeightChartScreen(),
      ),
    );
  }

  /// Navigate to the blood pressure chart screen
  void _navigateToBloodPressureChart(BuildContext context) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const BloodPressureChartScreen(),
      ),
    );
  }

  /// Navigate to the mood chart screen
  void _navigateToMoodChart(BuildContext context) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const MoodChartScreen(),
      ),
    );
  }
}

class _ChartNavigationCard extends StatelessWidget {
  final String title;
  final String description;
  final IconData icon;
  final Color color;
  final bool isAvailable;
  final VoidCallback? onTap;
  final String? comingSoonText;

  const _ChartNavigationCard({
    required this.title,
    required this.description,
    required this.icon,
    required this.color,
    required this.isAvailable,
    this.onTap,
    this.comingSoonText,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      child: InkWell(
        onTap: isAvailable ? onTap : null,
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Row(
            children: [
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: isAvailable 
                      ? color.withOpacity(0.15)
                      : Colors.grey.withOpacity(0.15),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(
                  icon,
                  size: 32,
                  color: isAvailable ? color : Colors.grey,
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Flexible(
                          child: Text(
                            title,
                            style: Theme.of(context).textTheme.titleMedium?.copyWith(
                              fontWeight: FontWeight.w600,
                              color: isAvailable ? null : Colors.grey,
                            ),
                          ),
                        ),
                        if (isAvailable) ...[
                          const SizedBox(width: 8),
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 2,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.green.withOpacity(0.15),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Text(
                              'NEW',
                              style: TextStyle(
                                fontSize: 10,
                                fontWeight: FontWeight.w600,
                                color: Colors.green.shade700,
                              ),
                            ),
                          ),
                        ],
                        if (!isAvailable && comingSoonText != null) ...[
                          const SizedBox(width: 8),
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 2,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.orange.withOpacity(0.15),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Text(
                              comingSoonText!,
                              style: TextStyle(
                                fontSize: 10,
                                fontWeight: FontWeight.w600,
                                color: Colors.orange.shade700,
                              ),
                            ),
                          ),
                        ],
                      ],
                    ),
                    const SizedBox(height: 4),
                    Text(
                      description,
                      style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                        color: isAvailable 
                            ? Theme.of(context).colorScheme.onSurface.withOpacity(0.7)
                            : Colors.grey,
                      ),
                    ),
                  ],
                ),
              ),
              Icon(
                isAvailable ? Icons.arrow_forward_ios : Icons.lock_outline,
                size: 16,
                color: isAvailable 
                    ? Theme.of(context).colorScheme.onSurface.withOpacity(0.5)
                    : Colors.grey,
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class _QuickStatsCard extends StatefulWidget {
  const _QuickStatsCard();

  @override
  State<_QuickStatsCard> createState() => _QuickStatsCardState();
}

class _QuickStatsCardState extends State<_QuickStatsCard> {
  final ChartDataService _chartService = ChartDataService();
  ChartData? _weightData;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _loadQuickStats();
  }

  Future<void> _loadQuickStats() async {
    setState(() => _isLoading = true);
    try {
      final weightData = await _chartService.getWeightChartData(
        timePeriod: ChartTimePeriod.oneMonth,
        displayUnit: UnitConstants.kgUnit,
      );
      setState(() {
        _weightData = weightData;
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.analytics_outlined,
                  color: Theme.of(context).colorScheme.primary,
                ),
                const SizedBox(width: 8),
                Text(
                  'Quick Stats',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            if (_isLoading)
              const Center(child: CircularProgressIndicator())
            else if (_weightData != null && _weightData!.isNotEmpty)
              _buildStatsContent()
            else
              _buildEmptyState(),
          ],
        ),
      ),
    );
  }

  Widget _buildStatsContent() {
    final stats = _weightData!.statistics;
    
    return Row(
      children: [
        Expanded(
          child: _buildStatItem(
            'Entries',
            stats.totalEntries.toString(),
            Icons.data_usage,
          ),
        ),
        Expanded(
          child: _buildStatItem(
            'Average',
            stats.formatAverage(_weightData!.unit),
            Icons.trending_flat,
          ),
        ),
        Expanded(
          child: _buildStatItem(
            'Trend',
            stats.formatWeightChange(_weightData!.unit),
            stats.weightChange != null && stats.weightChange! > 0
                ? Icons.trending_up
                : stats.weightChange != null && stats.weightChange! < 0
                    ? Icons.trending_down
                    : Icons.trending_flat,
          ),
        ),
      ],
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon) {
    return Column(
      children: [
        Icon(
          icon,
          size: 20,
          color: Theme.of(context).colorScheme.primary.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),
          ),
        ),
      ],
    );
  }

  Widget _buildEmptyState() {
    return Column(
      children: [
        Icon(
          Icons.info_outline,
          size: 32,
          color: Theme.of(context).colorScheme.primary.withOpacity(0.5),
        ),
        const SizedBox(height: 8),
        Text(
          'Start adding health data to see stats here',
          style: Theme.of(context).textTheme.bodyMedium?.copyWith(
            color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
          ),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }
}
