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 StatefulWidget {
  final dynamic exercise;
  final bool isReview;

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

  @override
  State<MatchingPairsQuestion> createState() => _MatchingPairsQuestionState();
}

class _MatchingPairsQuestionState extends State<MatchingPairsQuestion> {
  late List<dynamic> pairs;
  late List<String> originalRightPairs;
  late List<String> shuffledRightPairs;
  late Map<String, String> studentAnswers;
  late Map<String, String> originalPairMapping;
  late Map<String, int> originalPairIndices;

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

  // void initializePairs() {
  //   pairs = [];
  //   studentAnswers = {};
  //   originalPairMapping = {};
  //   originalPairIndices = {};

  //   if (widget.exercise is ExerciseModel) {
  //     // Mode Exercise
  //     pairs = (widget.exercise.choices as MatchingPair).pairs;
  //     final provider = Provider.of<ExerciseProvider>(context, listen: false);
  //     final currentIndex = provider.currentExerciseIndex;

  //     // Simpan indeks asli untuk setiap pasangan kiri
  //     for (int i = 0; i < pairs.length; i++) {
  //       originalPairIndices[pairs[i].left] = i;
  //     }

  //     originalRightPairs = pairs.map((pair) => pair.right as String).toList();
  //     shuffledRightPairs =
  //         List<String>.from(provider.shuffledRightPairsList[currentIndex]);
  //   } else if (widget.exercise is ReviewExerciseDetail) {
  //     // Mode Review
  //     if (widget.exercise.matchingPairs != null) {
  //       if (widget.exercise.answerStudent.isNotEmpty) {
  //         final answerPairs = widget.exercise.answerStudent.split(', ');

  //         // Buat pairs berdasarkan urutan jawaban siswa
  //         pairs = answerPairs.map((pair) {
  //           final parts = pair.split('-');
  //           return Pair(left: parts[0], right: parts[1]);
  //         }).toList();

  //         // Simpan indeks asli dan mapping untuk setiap pasangan
  //         for (int i = 0; i < pairs.length; i++) {
  //           final left = pairs[i].left;
  //           final right = pairs[i].right;
  //           originalPairIndices[left] = i;
  //           studentAnswers[left] = right;
  //           originalPairMapping[left] = right;
  //         }

  //         // Set originalRightPairs dan shuffledRightPairs sama dengan urutan jawaban siswa
  //         originalRightPairs =
  //             pairs.map((pair) => pair.right as String).toList();
  //         shuffledRightPairs =
  //             originalRightPairs.toList(); // Tidak diacak untuk review
  //       } else {
  //         // Jika tidak ada jawaban, gunakan data asli
  //         pairs = widget.exercise.matchingPairs!.map((reviewPair) {
  //           return Pair(
  //             left: reviewPair.leftPair,
  //             right: reviewPair.rightPair,
  //           );
  //         }).toList();

  //         // Simpan indeks asli untuk setiap pasangan
  //         for (int i = 0; i < pairs.length; i++) {
  //           originalPairIndices[pairs[i].left] = i;
  //         }

  //         originalRightPairs =
  //             pairs.map((pair) => pair.right as String).toList();
  //         shuffledRightPairs = originalRightPairs.toList();
  //       }
  //     }
  //   }

  //   // Bangun pemetaan konsisten
  //   for (int i = 0; i < pairs.length; i++) {
  //     final left = pairs[i].left;
  //     final right = pairs[i].right;
  //     originalPairMapping[left] = right;
  //   }
  // }

  void initializePairs() {
    pairs = [];
    studentAnswers = {};
    originalPairMapping = {};
    originalPairIndices = {};

    if (widget.exercise is ExerciseModel) {
      // Mode Exercise
      pairs = (widget.exercise.choices as MatchingPair).pairs;
      final provider = Provider.of<ExerciseProvider>(context, listen: false);
      final currentIndex = provider.currentExerciseIndex;

      // Simpan indeks asli untuk setiap pasangan kiri
      for (int i = 0; i < pairs.length; i++) {
        originalPairIndices[pairs[i].left] = i;
      }

      originalRightPairs = pairs.map((pair) => pair.right as String).toList();
      shuffledRightPairs =
          List<String>.from(provider.shuffledRightPairsList[currentIndex]);
    } else if (widget.exercise is ReviewExerciseDetail) {
      // Mode Review
      if (widget.exercise.matchingPairs != null) {
        // Gunakan data asli dari exercise untuk mempertahankan urutan
        pairs = widget.exercise.matchingPairs!.map((reviewPair) {
          return Pair(
            left: reviewPair.leftPair,
            right: reviewPair.rightPair,
          );
        }).toList();

        // Simpan indeks asli untuk setiap pasangan
        for (int i = 0; i < pairs.length; i++) {
          originalPairIndices[pairs[i].left] = i;
        }

        // Use the original right pairs without shuffling
        originalRightPairs = pairs.map((pair) => pair.right as String).toList();
        shuffledRightPairs =
            originalRightPairs.toList(); // No shuffling for review

        // Rekonstruksi jawaban siswa
        if (widget.exercise.answerStudent.isNotEmpty) {
          final answerPairs = widget.exercise.answerStudent.split(', ');
          studentAnswers = {
            for (var pair in answerPairs) pair.split('-')[0]: pair.split('-')[1]
          };
        }
      }
    }

    // Bangun pemetaan konsisten
    for (int i = 0; i < pairs.length; i++) {
      final left = pairs[i].left;
      final right = pairs[i].right;
      originalPairMapping[left] = right;
    }
  }

  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,
    bool isLeft,
    Map<String, String> studentAnswers,
  ) {
    bool isSelected = false;
    bool isActive = false;
    Color? color;

    // Mencari indeks asli pasangan untuk warna yang konsisten
    int originalPairIndex = -1;

    if (isLeft) {
      originalPairIndex = pairs.indexWhere((pair) =>
          pair is Pair ? pair.left == option : pair.leftPair == option);
      isActive = provider.activeLeftOption == option;
    } else {
      // Untuk right pair, cari berdasarkan pasangan yang sudah terbentuk
      if (widget.isReview) {
        // Untuk mode review, periksa apakah opsi ini ada di jawaban siswa
        final matchedLeft = studentAnswers.keys.firstWhere(
          (key) => studentAnswers[key] == option,
          orElse: () => '',
        );

        if (matchedLeft.isNotEmpty) {
          originalPairIndex = pairs.indexWhere((pair) => pair is Pair
              ? pair.left == matchedLeft
              : pair.leftPair == matchedLeft);
          isSelected = true;
        }
      } else {
        if (provider.hasMatchedPair(exerciseIndex, option)) {
          String? matchedLeft =
              provider.getMatchedLeftPair(exerciseIndex, option);
          if (matchedLeft != null) {
            originalPairIndex = pairs.indexWhere((pair) => pair is Pair
                ? pair.left == matchedLeft
                : pair.leftPair == matchedLeft);
          }
        }
      }
    }

    // Menentukan warna berdasarkan status
    if (widget.isReview) {
      if (isLeft) {
        // Untuk left pair di mode review
        final matchedRight = studentAnswers[option];
        if (matchedRight != null) {
          isSelected = true;
          // Cari indeks pasangan untuk warna yang konsisten
          originalPairIndex = pairs.indexWhere(
              (pair) => (pair is Pair ? pair.left : pair.leftPair) == option);
          color = _getPairColor(originalPairIndex);
        }
      } else {
        // Untuk right pair di mode review
        final matchedLeft = studentAnswers.keys.firstWhere(
          (key) => studentAnswers[key] == option,
          orElse: () => '',
        );

        if (matchedLeft.isNotEmpty) {
          isSelected = true;
          // Cari indeks pasangan untuk warna yang konsisten
          originalPairIndex = pairs.indexWhere((pair) =>
              (pair is Pair ? pair.left : pair.leftPair) == matchedLeft);
          color = _getPairColor(originalPairIndex);
        }
      }
    } else {
      isSelected = provider.isOptionSelected(exerciseIndex, option, isLeft);
      if (isSelected || isActive) {
        color = _getPairColor(originalPairIndex);
      }
    }

    return GestureDetector(
      onTap: widget.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 ?? _getPairColor(originalPairIndex)
              : (isActive
                  ? _getPairColor(originalPairIndex)
                  : 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 && !widget.isReview
              ? [
                  BoxShadow(
                    color: _getPairColor(originalPairIndex).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,
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<ExerciseProvider>(context);
    final currentIndex = provider.currentExerciseIndex;

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

          return Padding(
            padding: const EdgeInsets.only(bottom: 8.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: _buildOptionItem(
                    context,
                    left,
                    provider,
                    currentIndex,
                    true,
                    studentAnswers,
                  ),
                ),
                const SizedBox(width: 10),
                Expanded(
                  child: _buildOptionItem(
                    context,
                    right,
                    provider,
                    currentIndex,
                    false,
                    studentAnswers,
                  ),
                ),
              ],
            ),
          );
        }).toList(),
      ],
    );
  }
}
