import 'package:english_learning/core/widgets/custom_snackbar.dart';
import 'package:english_learning/features/learning/modules/exercises/models/review_exercise_model.dart';
import 'package:english_learning/features/learning/modules/exercises/providers/exercise_provider.dart';
import 'package:flutter/material.dart';
import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:english_learning/features/learning/modules/exercises/models/exercise_model.dart';
import 'package:provider/provider.dart';

class MatchingPairsQuestion extends StatelessWidget {
  final dynamic exercise;
  final bool isReview;

  const MatchingPairsQuestion({
    super.key,
    required this.exercise,
    this.isReview = false,
  });

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<ExerciseProvider>(context);
    List<dynamic> pairs = [];
    Map<String, String> studentAnswers = {};
    final currentIndex = provider.currentExerciseIndex;

    if (exercise is ExerciseModel) {
      pairs = (exercise.choices as MatchingPair).pairs;
    } else if (exercise is ReviewExerciseDetail) {
      if (exercise.matchingPairs != null) {
        pairs = exercise.matchingPairs!.map((reviewPair) {
          return Pair(
            left: reviewPair.leftPair,
            right: reviewPair.rightPair,
          );
        }).toList();

        // Parse student answers
        if (exercise.answerStudent.isNotEmpty) {
          final answerPairs = exercise.answerStudent.split(', ');
          for (var pair in answerPairs) {
            final parts = pair.split('-');
            if (parts.length == 2) {
              studentAnswers[parts[0]] = parts[1];
            }
          }
        }
      }
    }

    // Create a reverse mapping for easier lookup of left pair from right pair
    Map<String, String> reverseStudentAnswers = {};
    studentAnswers.forEach((left, right) {
      reverseStudentAnswers[right] = left;
    });

    return Column(
      children: [
        ...pairs.asMap().entries.map((entry) {
          int pairIndex = entry.key;
          dynamic pair = entry.value;
          String left = pair is Pair ? pair.left : pair.leftPair;
          String right = pair is Pair ? pair.right : pair.rightPair;

          // Get the corresponding color for this pair
          Color pairColor = _getPairColor(pairIndex);

          // Find if this item is matched in student answers
          String? studentMatchedRight = studentAnswers[left];
          String? matchedLeftForRight = reverseStudentAnswers[right];

          // Find the color index for the matched pair
          int? matchedPairIndex;
          if (isReview && matchedLeftForRight != null) {
            matchedPairIndex = pairs.indexWhere((p) {
              if (p is Pair) {
                return p.left == matchedLeftForRight;
              }
              return false;
            });
          }

          return Padding(
            padding: const EdgeInsets.only(bottom: 8.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: _buildOptionItem(
                    context,
                    left,
                    provider,
                    currentIndex,
                    pairIndex,
                    true,
                    studentMatchedRight != null,
                    studentAnswers,
                    pairColor,
                  ),
                ),
                const SizedBox(width: 10),
                Expanded(
                  child: _buildOptionItem(
                    context,
                    right,
                    provider,
                    currentIndex,
                    matchedPairIndex ?? pairIndex,
                    false,
                    matchedLeftForRight != null,
                    studentAnswers,
                    matchedPairIndex != null
                        ? _getPairColor(matchedPairIndex)
                        : pairColor,
                  ),
                ),
              ],
            ),
          );
        }).toList(),
      ],
    );
  }

  Color _getPairColor(int index) {
    final List<Color> colors = [
      Colors.blue,
      Colors.green,
      Colors.orange,
      Colors.purple,
      Colors.red,
    ];
    return colors[index % colors.length];
  }

  Widget _buildOptionItem(
    BuildContext context,
    String option,
    ExerciseProvider provider,
    int exerciseIndex,
    int pairIndex,
    bool isLeft,
    bool isMatched,
    Map<String, String> studentAnswers,
    Color pairColor,
  ) {
    Color? color;
    bool isSelected = false;
    bool isActive = false;

    if (isReview) {
      if (isMatched) {
        color = pairColor;
        isSelected = true;
      }
    } else {
      if (isLeft) {
        color = provider.getLeftColor(exerciseIndex, pairIndex);
        isActive = provider.activeLeftOption == option;
      } else {
        color = provider.getRightColor(exerciseIndex, pairIndex);
      }
      isSelected = provider.isOptionSelected(exerciseIndex, option, isLeft);
    }

    return GestureDetector(
      onTap: isReview
          ? null
          : () {
              if (!isLeft && provider.activeLeftOption == null) {
                CustomSnackBar.show(
                  context,
                  message: 'Please select a left option first.',
                  isError: true,
                );
              } else {
                provider.answerQuestion(exerciseIndex, option);
              }
            },
      child: Container(
        decoration: BoxDecoration(
          color: isSelected
              ? color ?? pairColor
              : (isActive ? pairColor : AppColors.whiteColor),
          borderRadius: const BorderRadius.only(
            topRight: Radius.circular(20),
            bottomRight: Radius.circular(20),
            bottomLeft: Radius.circular(20),
          ),
          border: Border.all(
            color: isSelected
                ? color ?? AppColors.cardDisabledColor
                : AppColors.cardDisabledColor,
            width: isSelected ? 2 : 1,
          ),
          boxShadow: isActive && !isReview
              ? [
                  BoxShadow(
                    color: pairColor.withOpacity(0.5),
                    spreadRadius: 1,
                    blurRadius: 4,
                    offset: const Offset(0, 2),
                  )
                ]
              : null,
        ),
        padding: const EdgeInsets.symmetric(horizontal: 14.0, vertical: 10.0),
        child: Text(
          option,
          style: AppTextStyles.blackTextStyle.copyWith(
            fontWeight: FontWeight.w900,
            color: isSelected || isActive
                ? AppColors.whiteColor
                : AppColors.blackColor,
          ),
        ),
      ),
    );
  }
}
