import 'dart:convert';

import 'package:byod/helper/prefs.dart';
import 'package:byod/helper/widget/style.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../../api/api.dart';
import '../../bloc/feedback_option.dart';
import '../../bloc/feedback_select.dart';
import '../../bloc/view_bill.dart';
import '../../models/bill.dart';
import '../../models/feedback_option.dart';
import '../../models/rate_value_selected.dart';
import '../helper.dart';

class EmoticonRateNew extends StatelessWidget {
  const EmoticonRateNew({
    Key? key,
    required this.sizeImage,
    required this.rateNote,
    required this.isHistory,
    required this.dataBill,
    this.orderId = '',
  }) : super(key: key);

  final double sizeImage;
  final TextEditingController rateNote;
  final bool isHistory;
  final List<Bill> dataBill;
  final String orderId;

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<FeedbackSelect, RateValueSelected>(
      builder: (contextSelectedFB, valueSelected) {
        return BlocBuilder<FeedBackOptionBloc, List<FeedBackOption>>(
          builder: (contextFeedback, listOption) {
            List<String> feedBakcAnswer = [];
            String header = '';
            // List<String> feedBakcAnswerSelected = [];
            if (valueSelected.ratingFeedback != noRate) {
              int indexOption = listOption.indexWhere((option) =>
                  option.feedBackOptionValue == valueSelected.ratingFeedback);
              if (indexOption != -1) {
                feedBakcAnswer = listOption[indexOption].feedBackAnswer;
                header = listOption[indexOption].header;
              }
            }
            return GestureDetector(
              onTap: () {
                FocusScopeNode currentFocus = FocusScope.of(context);

                if (!currentFocus.hasPrimaryFocus) {
                  currentFocus.unfocus();
                }
              },
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    padding: const EdgeInsets.only(top: 8),
                    height: 3,
                    width: 50,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(7),
                      color: greyColor,
                    ),
                  ),
                  const SizedBox(
                    height: 40,
                  ),
                  defaultText(
                    context,
                    'Bagaimana pengalaman anda bertransaksi di excelso ?',
                    textAlign: TextAlign.center,
                    style: emojiStyle(),
                  ),
                  const SizedBox(
                    height: 19,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      GestureDetector(
                        onTap: () {
                          // setState(() {
                          //   rateValue = badRate;
                          // });
                          context
                              .read<FeedbackSelect>()
                              .select(valueSelected, badRate, '', '');
                        },
                        child: Image(
                          width: sizeImage,
                          height: sizeImage,
                          image: AssetImage(
                              (valueSelected.ratingFeedback == badRate)
                                  ? 'assets/emoji/bad.png'
                                  : 'assets/emoji/bad_grey.png'),
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          // setState(() {
                          //   rateValue = badRate;
                          // });
                          context
                              .read<FeedbackSelect>()
                              .select(valueSelected, neutralRate, '', '');
                        },
                        child: Image(
                          width: sizeImage,
                          height: sizeImage,
                          image: AssetImage(
                              (valueSelected.ratingFeedback == neutralRate)
                                  ? 'assets/emoji/neutral.png'
                                  : 'assets/emoji/neutral_grey.png'),
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          // setState(() {
                          //   rateValue = badRate;
                          // });
                          context
                              .read<FeedbackSelect>()
                              .select(valueSelected, goodRate, '', '');
                        },
                        child: Image(
                          width: sizeImage,
                          height: sizeImage,
                          image: AssetImage(
                              (valueSelected.ratingFeedback == goodRate)
                                  ? 'assets/emoji/good.png'
                                  : 'assets/emoji/good_grey.png'),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(
                    height: 33,
                  ),
                  defaultText(
                    context,
                    header,
                    style: emojiStyle(
                      font: 14,
                    ),
                  ),
                  const SizedBox(
                    height: 10,
                  ),
                  Wrap(
                    crossAxisAlignment: WrapCrossAlignment.start,
                    alignment: WrapAlignment.start,
                    spacing: 14,
                    runSpacing: 14,
                    children: [
                      for (var feedback in feedBakcAnswer)
                        GestureDetector(
                          onTap: () {
                            context.read<FeedbackSelect>().select(valueSelected,
                                valueSelected.ratingFeedback, feedback, '');
                          },
                          child: Container(
                            padding: const EdgeInsets.symmetric(
                              vertical: 4,
                              horizontal: 11,
                            ),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(3),
                              border: Border.all(
                                color: const Color(0xffB0BEC5),
                              ),
                              color: (valueSelected.answerOption
                                      .contains(feedback))
                                  ? selectedColor
                                  : null,
                            ),
                            child: defaultText(
                              context,
                              feedback,
                              style: emojiStyle(
                                  font: 12,
                                  fontWeight: FontWeight.w400,
                                  color: const Color(0xff212121)),
                            ),
                          ),
                        ),
                    ],
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  TextField(
                    maxLines: 4,
                    keyboardType: TextInputType.text,
                    textInputAction: TextInputAction.done,
                    controller: rateNote,
                    maxLength: maxLengthTextField,
                    decoration: const InputDecoration(
                        labelText: 'Beri Masukan',
                        labelStyle: TextStyle(
                          fontFamily: 'OpenSans',
                          fontSize: 12,
                          fontWeight: FontWeight.w600,
                          color: textColorBlack,
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderSide: BorderSide(width: 1, color: greyColor),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderSide: BorderSide(width: 1, color: greyColor),
                        )),
                    style: textStyleNormalFont(context),
                    // decoration: const InputDecoration(
                    //   labelText: 'Beri Masukkan',
                    //   labelStyle: TextStyle(
                    //     fontFamily: 'OpenSans',
                    //     fontSize: 14,
                    //     color: textColorModalHeaderNama,
                    //   ),
                    // ),
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  GestureDetector(
                    onTap: () async {
                      if (valueSelected.ratingFeedback == noRate) {
                        EasyLoading.showToast('Anda belum memilih rating');
                      } else {
                        Api.sendFeedBack(
                          valueSelected.ratingFeedback,
                          rateNote.text,
                          dataBill[0].id,
                          valueSelected.answerOption,
                        ).then((value) {
                          Navigator.pop(context);
                          if (!isHistory) {
                            context.read<ViewBillBloc>().getBill();
                          } else {
                            List<String> listHistory = getListHistory();
                            if (listHistory.isNotEmpty) {
                              int indexHistory = listHistory.indexWhere(
                                (listHistory) =>
                                    jsonDecode(listHistory)['order_id'] ==
                                    orderId,
                              );
                              if (indexHistory != -1) {
                                dynamic jsonDecodeHistory =
                                    jsonDecode(listHistory[indexHistory]);
                                context.read<ViewBillBloc>().getBill(
                                      orderIdH: jsonDecodeHistory['order_id'],
                                      branchCodeH:
                                          jsonDecodeHistory['branch_code'],
                                      brandCodeH: jsonDecodeHistory['brand'],
                                      tableNumberH: jsonDecodeHistory['table'],
                                      tokenH: jsonDecodeHistory['token'],
                                      userNameH: jsonDecodeHistory['user_name'],
                                    );
                              } else {
                                context.read<ViewBillBloc>().getBill();
                              }
                            } else {
                              context.read<ViewBillBloc>().getBill();
                            }
                          }
                        });
                      }
                    },
                    child: Container(
                      height: 43,
                      decoration: BoxDecoration(
                        color: buttonColor,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Center(
                        child: defaultText(
                          context,
                          'Kirim Masukan',
                          style: rincianPembayaran(
                            color: textInButton,
                            fontWeight: FontWeight.w400,
                            font: 14,
                          ),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(
                    height: 5,
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: Container(
                      height: 43,
                      decoration: BoxDecoration(
                        color: Colors.transparent,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Center(
                        child: defaultText(
                          context,
                          'Lewati',
                          style: rincianPembayaran(
                            color: textColorBlack,
                            fontWeight: FontWeight.w400,
                            font: 14,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }
}
