// SPDX-FileCopyrightText: © 2025 Nøkken.io <nokken.io@proton.me>
// SPDX-License-Identifier: AGPL-3.0
//
// correlations_chart.dart
//
import 'package:flutter/material.dart';
import 'dart:math' as math;
import 'package:nokken/src/core/ui/theme/app_colors.dart';
import 'package:nokken/src/core/ui/theme/app_text_styles.dart';
import 'package:nokken/src/features/stats/models/stat_analysis.dart';

/// A widget that displays correlation relationships between different factors as a visual chart.
///
/// This chart visualizes the strength of relationships between factors,
/// with correlation bars extending from left to right. The chart includes
/// scale markers at 0.25, 0.5, 0.75, and 1.0.
///
/// Each factor can be tapped to navigate to its detailed analysis when [onFactorTap] is provided.
class CorrelationsChart extends StatelessWidget {
  final List<FactorRelationship> relationships;
  final double height;
  final Function(String)? onFactorTap;

  const CorrelationsChart({
    super.key,
    required this.relationships,
    this.height = 400,
    this.onFactorTap,
  });

  @override
  Widget build(BuildContext context) {
    // Sort relationships by strength (descending)
    final sortedRelationships = List<FactorRelationship>.from(relationships)
      ..sort((a, b) => b.strength.abs().compareTo(a.strength.abs()));

    // Height calculation that accounts for the content
    final calculatedHeight = math.min(
      700.0, // Cap maximum height
      math.max(height, sortedRelationships.length * 80.0),
    );

    return SizedBox(
      height: calculatedHeight,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // Chart items
          Expanded(
            child: ListView.separated(
              physics:
                  const ClampingScrollPhysics(), // Prevents overscroll effect
              padding: EdgeInsets.zero,
              itemCount: sortedRelationships.length,
              separatorBuilder: (context, index) => Divider(
                color: Colors.white,
                height: 24,
                thickness: 1.5,
              ),
              itemBuilder: (context, index) {
                return _buildChartItem(sortedRelationships[index], context);
              },
            ),
          ),
        ],
      ),
    );
  }

  /// Builds a single chart item representing one relationship
  ///
  /// Each chart item includes factor buttons at the top and a correlation bar below
  /// showing the strength of the relationship.
  Widget _buildChartItem(
      FactorRelationship relationship, BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Factor buttons
        _buildFactorButtons(relationship),
        const SizedBox(height: 12),

        // Correlation bar
        SizedBox(
          height: 28,
          child: LayoutBuilder(
            builder: (context, constraints) {
              final chartWidth = constraints.maxWidth;
              // Use full width for the bar
              final maxBarWidth = chartWidth;
              // Calculate bar width based on strength
              final barWidth = maxBarWidth * relationship.strength.abs();

              return Stack(
                clipBehavior: Clip.none,
                children: [
                  // Guidelines at 0, 0.25, 0.5, 0.75, 1.0
                  // Draw vertical lines for guidelines
                  Positioned(
                    left: 0, // 0 position (start)
                    top: 0,
                    bottom: 0,
                    child:
                        Container(width: 1, color: AppColors.surfaceContainer),
                  ),
                  Positioned(
                    left: chartWidth * 0.25, // 0.25 position
                    top: 0,
                    bottom: 0,
                    child: Container(
                        width: 1,
                        color: AppColors.surfaceContainer.withAlpha(180)),
                  ),
                  Positioned(
                    left: chartWidth * 0.5, // 0.5 position
                    top: 0,
                    bottom: 0,
                    child: Container(
                        width: 1,
                        color: AppColors.surfaceContainer.withAlpha(180)),
                  ),
                  Positioned(
                    left: chartWidth * 0.75, // 0.75 position
                    top: 0,
                    bottom: 0,
                    child: Container(
                        width: 1,
                        color: AppColors.surfaceContainer.withAlpha(180)),
                  ),
                  Positioned(
                    left: chartWidth, // 1.0 position (end)
                    top: 0,
                    bottom: 0,
                    child: Container(
                        width: 1,
                        color: AppColors.surfaceContainer.withAlpha(180)),
                  ),

                  // Add scale labels below the guidelines
                  Positioned(
                    left: 0 - 5,
                    bottom: -22,
                    child: Text('',
                        style: AppTextStyles.bodySmall.copyWith(fontSize: 10)),
                  ),
                  Positioned(
                    left: chartWidth * 0.25 - 10,
                    bottom: -22,
                    child: Text('.25',
                        style: AppTextStyles.bodySmall.copyWith(fontSize: 10)),
                  ),
                  Positioned(
                    left: chartWidth * 0.5 - 10,
                    bottom: -22,
                    child: Text('.5',
                        style: AppTextStyles.bodySmall.copyWith(fontSize: 10)),
                  ),
                  Positioned(
                    left: chartWidth * 0.75 - 10,
                    bottom: -22,
                    child: Text('.75',
                        style: AppTextStyles.bodySmall.copyWith(fontSize: 10)),
                  ),
                  Positioned(
                    left: chartWidth - 10,
                    bottom: -22,
                    child: Text('1',
                        style: AppTextStyles.bodySmall.copyWith(fontSize: 10)),
                  ),

                  // Correlation bar - always starts at left (0)
                  Positioned(
                    left: 0, // Always start at left edge
                    top: 0,
                    height: 28,
                    width: barWidth,
                    child: Container(
                      decoration: BoxDecoration(
                        color: relationship.relationshipColor,
                        borderRadius: BorderRadius.circular(4),
                      ),
                    ),
                  ),
                ],
              );
            },
          ),
        ),
        const SizedBox(height: 22),
      ],
    );
  }

  Widget _buildFactorButtons(FactorRelationship relationship) {
    // Typically we have 2 factors in a relationship
    if (relationship.factorNames.length < 2) {
      return _buildSingleFactorButton(relationship.factorNames.first);
    }

    // Build row with both factor buttons and "and" text between
    return Row(
      mainAxisAlignment: MainAxisAlignment.start, // Left align the row
      children: [
        // First factor button
        _buildSingleFactorButton(relationship.factorNames[0]),

        // "and" text between buttons
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8.0),
          child: Text(
            "and",
            style: AppTextStyles.bodyMedium,
          ),
        ),

        // Second factor button
        _buildSingleFactorButton(relationship.factorNames[1]),
      ],
    );
  }

  Widget _buildSingleFactorButton(String factorName) {
    return ElevatedButton(
      onPressed: onFactorTap != null ? () => onFactorTap!(factorName) : null,
      style: ElevatedButton.styleFrom(
        padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 6.0),
        backgroundColor: AppColors.primary.withAlpha(20),
        foregroundColor: AppColors.primary,
        elevation: 0,
        alignment: Alignment.centerLeft, // Left align text inside button
        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
      ),
      child: Text(
        factorName,
        style: AppTextStyles.bodyMedium.copyWith(
          color: AppColors.primary,
        ),
        textAlign: TextAlign.left, // Left align text
        overflow: TextOverflow.ellipsis,
      ),
    );
  }
}
