// ABOUTME: Chart legend widget for displaying statistics and chart information
// ABOUTME: Shows key metrics like average, range, trend, and data point count

import 'package:flutter/material.dart';
import 'package:albi/services/chart_data_service.dart';
import 'package:albi/utils/constants.dart';

/// Widget that displays chart statistics and legend information
class ChartLegend extends StatelessWidget {
  final ChartData chartData;
  final bool showTrend;
  final bool compact;
  final String? selectedUnit;

  const ChartLegend({
    super.key,
    required this.chartData,
    this.showTrend = true,
    this.compact = false,
    this.selectedUnit,
  });

  @override
  Widget build(BuildContext context) {
    final statistics = chartData.statistics;
    final unit = selectedUnit ?? chartData.unit;

    if (chartData.isEmpty) {
      return _buildEmptyState(context);
    }

    if (compact) {
      return _buildCompactLegend(context, statistics, unit);
    }

    return _buildFullLegend(context, statistics, unit);
  }

  /// Build empty state when no data is available
  Widget _buildEmptyState(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            Icon(
              Icons.info_outline,
              size: 32,
              color: Theme.of(context).colorScheme.primary.withOpacity(0.5),
            ),
            const SizedBox(height: 8),
            Text(
              'No data available for selected period',
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: Theme.of(context).colorScheme.onSurface.withOpacity(0.7),
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  /// Build compact version of the legend (single row)
  Widget _buildCompactLegend(BuildContext context, ChartStatistics statistics, String unit) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            _buildStatItem(
              context,
              'Avg',
              statistics.formatAverage(unit),
              Icons.trending_flat,
              compact: true,
            ),
            _buildDivider(),
            _buildStatItem(
              context,
              'Range',
              statistics.formatRange(unit),
              Icons.straighten,
              compact: true,
            ),
            if (showTrend && statistics.weightChange != null) ...[
              _buildDivider(),
              _buildStatItem(
                context,
                'Change',
                statistics.formatWeightChange(unit),
                _getTrendIcon(statistics.weightChange),
                color: _getTrendColor(context, statistics.weightChange),
                compact: true,
              ),
            ],
          ],
        ),
      ),
    );
  }

  /// Build full detailed legend
  Widget _buildFullLegend(BuildContext context, ChartStatistics statistics, String unit) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.analytics,
                  size: 20,
                  color: Theme.of(context).colorScheme.primary,
                ),
                const SizedBox(width: 8),
                Text(
                  'Statistics',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            _buildStatisticsGrid(context, statistics, unit),
            if (showTrend && chartData.trendLine != null) ...[
              const SizedBox(height: 16),
              _buildTrendLegend(context),
            ],
          ],
        ),
      ),
    );
  }

  /// Build statistics grid layout
  Widget _buildStatisticsGrid(BuildContext context, ChartStatistics statistics, String unit) {
    return Column(
      children: [
        Row(
          children: [
            Expanded(
              child: _buildStatItem(
                context,
                'Average',
                statistics.formatAverage(unit),
                Icons.trending_flat,
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _buildStatItem(
                context,
                'Total Entries',
                statistics.totalEntries.toString(),
                Icons.data_usage,
              ),
            ),
          ],
        ),
        const SizedBox(height: 12),
        Row(
          children: [
            Expanded(
              child: _buildStatItem(
                context,
                'Minimum',
                statistics.minimum != null 
                    ? '${_formatValue(statistics.minimum!, unit)} $unit'
                    : 'N/A',
                Icons.south,
                color: Colors.blue,
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _buildStatItem(
                context,
                'Maximum',
                statistics.maximum != null 
                    ? '${_formatValue(statistics.maximum!, unit)} $unit'
                    : 'N/A',
                Icons.north,
                color: Colors.orange,
              ),
            ),
          ],
        ),
        if (showTrend && statistics.weightChange != null) ...[
          const SizedBox(height: 12),
          Row(
            children: [
              Expanded(
                child: _buildStatItem(
                  context,
                  'Overall Change',
                  statistics.formatWeightChange(unit),
                  _getTrendIcon(statistics.weightChange),
                  color: _getTrendColor(context, statistics.weightChange),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: _buildStatItem(
                  context,
                  'Daily Trend',
                  statistics.trend != null 
                      ? '${statistics.trend! >= 0 ? '+' : ''}${_formatValue(statistics.trend!, unit)} $unit/day'
                      : 'N/A',
                  statistics.trend != null && statistics.trend! > 0 
                      ? Icons.trending_up 
                      : statistics.trend != null && statistics.trend! < 0
                          ? Icons.trending_down
                          : Icons.trending_flat,
                  color: statistics.trend != null 
                      ? _getTrendColor(context, statistics.trend)
                      : null,
                ),
              ),
            ],
          ),
        ],
      ],
    );
  }

  /// Build individual statistic item
  Widget _buildStatItem(
    BuildContext context,
    String label,
    String value,
    IconData icon, {
    Color? color,
    bool compact = false,
  }) {
    final itemColor = color ?? Theme.of(context).colorScheme.onSurface;
    
    if (compact) {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            size: 16,
            color: itemColor.withOpacity(0.7),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: Theme.of(context).textTheme.labelSmall?.copyWith(
              color: itemColor.withOpacity(0.7),
              fontSize: 10,
            ),
          ),
          Text(
            value,
            style: Theme.of(context).textTheme.bodySmall?.copyWith(
              color: itemColor,
              fontWeight: FontWeight.w600,
              fontSize: 12,
            ),
          ),
        ],
      );
    }

    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surface,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: Theme.of(context).colorScheme.outline.withOpacity(0.2),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                icon,
                size: 16,
                color: itemColor.withOpacity(0.7),
              ),
              const SizedBox(width: 6),
              Text(
                label,
                style: Theme.of(context).textTheme.labelMedium?.copyWith(
                  color: itemColor.withOpacity(0.7),
                ),
              ),
            ],
          ),
          const SizedBox(height: 4),
          Text(
            value,
            style: Theme.of(context).textTheme.titleSmall?.copyWith(
              color: itemColor,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      ),
    );
  }

  /// Build trend line legend
  Widget _buildTrendLegend(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.primary.withOpacity(0.05),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: Theme.of(context).colorScheme.primary.withOpacity(0.2),
        ),
      ),
      child: Row(
        children: [
          // Trend line indicator
          Container(
            width: 24,
            height: 2,
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.primary.withOpacity(0.6),
              borderRadius: BorderRadius.circular(1),
            ),
            child: CustomPaint(
              painter: DashedLinePainter(
                color: Theme.of(context).colorScheme.primary.withOpacity(0.6),
              ),
            ),
          ),
          const SizedBox(width: 12),
          Text(
            'Trend Line',
            style: Theme.of(context).textTheme.labelMedium?.copyWith(
              color: Theme.of(context).colorScheme.primary,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  /// Build divider for compact layout
  Widget _buildDivider() {
    return Container(
      width: 1,
      height: 32,
      color: Colors.grey.withOpacity(0.3),
    );
  }

  /// Get appropriate trend icon based on value
  IconData _getTrendIcon(double? value) {
    if (value == null) return Icons.trending_flat;
    if (value > 0.1) return Icons.trending_up;
    if (value < -0.1) return Icons.trending_down;
    return Icons.trending_flat;
  }

  /// Get appropriate trend color based on value
  Color _getTrendColor(BuildContext context, double? value) {
    if (value == null) return Theme.of(context).colorScheme.onSurface;
    if (value > 0.1) return Colors.red;
    if (value < -0.1) return Colors.green;
    return Theme.of(context).colorScheme.onSurface;
  }

  /// Format value with appropriate decimal places
  String _formatValue(double value, String unit) {
    final decimalPlaces = unit == UnitConstants.stonesUnit ? 2 : 1;
    return value.toStringAsFixed(decimalPlaces);
  }
}

/// Custom painter for dashed trend line indicator
class DashedLinePainter extends CustomPainter {
  final Color color;
  final double strokeWidth;

  DashedLinePainter({
    required this.color,
    this.strokeWidth = 2.0,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = color
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke;

    const dashWidth = 3.0;
    const dashSpace = 2.0;
    double startX = 0;

    while (startX < size.width) {
      final endX = (startX + dashWidth).clamp(0.0, size.width);
      canvas.drawLine(
        Offset(startX, size.height / 2),
        Offset(endX, size.height / 2),
        paint,
      );
      startX += dashWidth + dashSpace;
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
