import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/extensions/collection_extension.dart';
import 'package:mypoint_flutter_app/screen/quiz_campaign/quiz_campaign_header.dart';
import 'package:mypoint_flutter_app/screen/quiz_campaign/quiz_campaign_model.dart';
import 'package:mypoint_flutter_app/screen/quiz_campaign/quiz_campaign_viewmodel.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../resources/base_color.dart';
import '../../widgets/alert/data_alert_model.dart';
import '../../widgets/custom_empty_widget.dart';

class SurveyQuestionScreen extends BaseScreen {
  const SurveyQuestionScreen({super.key});

  @override
  State<SurveyQuestionScreen> createState() => _SurveyQuestionScreenState();
}

class _SurveyQuestionScreenState extends BaseState<SurveyQuestionScreen> with BasicState {
  late final QuizCampaignViewModel _viewModel;
  int currentIndex = 0;
  FocusNode? _textFocusNode;

  @override
  void initState() {
    super.initState();
    _textFocusNode = FocusNode();
    String? quizId;
    final args = Get.arguments;
    if (args is Map) {
      quizId = args['quizId'];
    }
    if (quizId == null && quizId == null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        Get.back();
      });
      return;
    }
    _viewModel = Get.put(QuizCampaignViewModel(quizId: quizId));
    _viewModel.onShowAlertError = (message, {shouldQuitScreen = false}) {
      if (message.isNotEmpty) {
        showAlertError(content: message,
          onConfirmed: shouldQuitScreen ? _onQuitScreen : null,
        );
      }
    };
    _viewModel.quizCampaignSubmitResponse = (popup) {
      showPopup(data: popup);
    };
    _viewModel.getQuizCampaignDetail();
  }

  _onQuitScreen() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Get.back();
    });
  }

  @override
  void dispose() {
    _textFocusNode?.dispose();
    super.dispose();
  }

  @override
  Widget createBody() {
    final textController = TextEditingController();
    final bottomSpace = MediaQuery.of(context).padding.bottom;
    return Scaffold(
      body: Obx(() {
        final questions = _viewModel.surveyData.value?.questions ?? [];
        final currentQuestion = questions.safe(currentIndex);
        final isLastQuestion = currentIndex == questions.length - 1;
        final qType = currentQuestion?.qType;
        if (qType == SurveyQuestionType.textarea) {
          textController.text = currentQuestion?.inputText ?? '';
        }
        if (currentQuestion == null) {
          return const EmptyWidget();
        }
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            QuizCampaignHeader(
              currentIndex: currentIndex,
              total: questions.length,
              onBackPressed: _showAlertConfirmQuitSurvey,
            ),
            Expanded(
              child: QuizCampaignContainer(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.only(bottom: 8),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Câu ${currentIndex + 1}/${questions.length}: ${qType?.textDes ?? ''}',
                        style: const TextStyle(fontWeight: FontWeight.w600, color: Colors.black54),
                      ),
                      const SizedBox(height: 8),
                      Text(
                        currentQuestion.text ?? '',
                        style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 12),
                      if (qType == SurveyQuestionType.textarea)
                        TextField(
                          focusNode: _textFocusNode,
                          controller: textController,
                          maxLines: 10,
                          decoration: InputDecoration(
                            hintText: 'Nhập câu trả lời của bạn',
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(12),
                              borderSide: BorderSide(color: Colors.grey.shade300),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(12),
                              borderSide: BorderSide(color: Colors.grey.shade300),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(12),
                              borderSide: const BorderSide(color: Color(0xFFEC4A53), width: 1.5),
                            ),
                          ),
                          onChanged: (value) {
                            currentQuestion?.inputText = value;
                          },
                        ),
                      ...List.generate(currentQuestion.choices?.length ?? 0, (index) {
                        final choice = currentQuestion.choices![index];
                        final isSelected = choice.isSelected == true;
                        return Padding(
                          padding: const EdgeInsets.only(bottom: 8.0),
                          child: InkWell(
                            onTap: () {
                              setState(() {
                                if (qType == SurveyQuestionType.radio) {
                                  for (final c in currentQuestion.choices!) {
                                    c.isSelected = false;
                                  }
                                  choice.isSelected = true;
                                } else if (qType == SurveyQuestionType.checkbox) {
                                  choice.isSelected = !(choice.isSelected ?? false);
                                }
                              });
                            },
                            child: Container(
                              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                border: Border.all(
                                  color: isSelected ? BaseColor.primary400 : Colors.grey.shade300,
                                  width: 1.5,
                                ),
                                borderRadius: BorderRadius.circular(12),
                              ),
                              child: Row(
                                children: [
                                  if (qType == SurveyQuestionType.radio)
                                    Radio<String>(
                                      activeColor: BaseColor.primary400,
                                      value: choice.value ?? '',
                                      groupValue:
                                          currentQuestion.choices!.firstWhereOrNull((e) => e.isSelected == true)?.value,
                                      onChanged: (_) {},
                                    ),
                                  if (qType == SurveyQuestionType.checkbox)
                                    Checkbox(value: isSelected, onChanged: (_) {}, activeColor: BaseColor.primary400),
                                  const SizedBox(width: 8),
                                  Expanded(child: Text(choice.value ?? '', style: const TextStyle(fontSize: 16))),
                                ],
                              ),
                            ),
                          ),
                        );
                      }),
                    ],
                  ),
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.only(left: 20, right: 20, bottom: bottomSpace),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  OutlinedButton(
                    onPressed: currentIndex > 0 ? _prev : null,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      foregroundColor: BaseColor.primary400,
                    ),
                    child: Text('Trước', style: TextStyle(fontSize: 16)),
                  ),
                  ElevatedButton(
                    onPressed: (currentQuestion.required == true && !currentQuestion.answered) ? null : _next,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: isLastQuestion ? Colors.redAccent : Colors.white, // Màu nền
                      foregroundColor: isLastQuestion ? Colors.white : BaseColor.primary400, // Màu chữ/icon
                    ),
                    child: Text(isLastQuestion ? 'Hoàn thành' : 'Tiếp', style: TextStyle(fontSize: 16)),
                  ),
                ],
              ),
            ),
          ],
        );
      }),
      backgroundColor: const Color(0xFFFFF1F3),
    );
  }

  _next() {
    if (currentIndex < (_viewModel.surveyData.value?.questions?.length ?? 0) - 1) {
      setState(() => currentIndex++);
    } else {
      _textFocusNode?.unfocus();
      Future.delayed(Duration(milliseconds: 100), () {
        _showAlertConfirmSubmit();
      });
    }
  }

  void _prev() {
    if (currentIndex > 0) {
      setState(() => currentIndex--);
    }
  }

  _showAlertConfirmSubmit() {
    final dataAlert = DataAlertModel(
      title: "Xác nhận",
      description: "Bạn chắc chắn muốn nộp khảo sát? Sau khi gửi, bạn sẽ không thể thay đổi câu trả lời.",
      localHeaderImage: "assets/images/ic_pipi_05.png",
      buttons: [
        AlertButton(
          text: "Đồng ý",
          onPressed: () {
            Get.back();
            _viewModel.quizCampaignSubmit();
          },
          bgColor: BaseColor.primary500,
          textColor: Colors.white,
        ),
        AlertButton(text: "Huỷ", onPressed: () => Get.back(), bgColor: Colors.white, textColor: BaseColor.second500),
      ],
    );
    showAlert(data: dataAlert);
  }

  _showAlertConfirmQuitSurvey() {
    final dataAlert = DataAlertModel(
      description: "Có vẻ bạn chưa hoàn thành nhiệm vụ rồi. Tiếp tục nhé!!",
      localHeaderImage: "assets/images/ic_pipi_03.png",
      buttons: [
        AlertButton(
          text: "Thực hiện",
          onPressed: () {
            Get.back();
          },
          bgColor: BaseColor.primary500,
          textColor: Colors.white,
        ),
        AlertButton(
          text: "Thoát",
          onPressed: () {
            Get.back();
            Get.back();
          },
          bgColor: Colors.white,
          textColor: BaseColor.second500,
        ),
      ],
    );
    showAlert(data: dataAlert);
  }
}

extension FirstWhereOrNullExtension<E> on Iterable<E> {
  E? firstWhereOrNull(bool Function(E) test) {
    for (var element in this) {
      if (test(element)) return element;
    }
    return null;
  }
}

class QuizCampaignContainer extends StatelessWidget {
  final Widget child;
  const QuizCampaignContainer({super.key, required this.child});

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 16, right: 16, bottom: 16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        // border: Border.all(color: Colors.redAccent.shade100, width: 1),
      ),
      child: child,
    );
  }
}
