// ignore_for_file: avoid_unnecessary_containers, sized_box_for_whitespace, must_be_immutable

import 'dart:convert';

import 'package:byod/bloc/feedback_option.dart';
import 'package:byod/main.dart';
import 'package:byod/models/bill.dart';
import 'package:byod/models/feedback_option.dart';
import 'package:byod/models/rate_value_selected.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_select.dart';
import '../../bloc/view_bill.dart';
import '../helper.dart';
import 'style.dart';

class EmoticonRate extends StatefulWidget {
  Bill bill;
  bool isHistory;
  String sessionId;
  EmoticonRate({
    Key? key,
    required this.bill,
    this.isHistory = false,
    this.sessionId = '',
  }) : super(key: key);

  @override
  State<EmoticonRate> createState() => _EmoticonRateState();
}

class _EmoticonRateState extends State<EmoticonRate> {
  // int? rateValue;
  final rateNote = TextEditingController();
  @override
  Widget build(BuildContext context) {
    double widthScreen = responsiveWidthScreen(context);
    return BlocBuilder<FeedbackSelect, RateValueSelected>(
        builder: (context, valueSelected) {
      // if (valueSelected.ratingFeedback != noRate) {
      //   print(valueSelected.answerOption);
      // }
      return BlocBuilder<FeedBackOptionBloc, List<FeedBackOption>>(
        builder: (context, 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 SingleChildScrollView(
            child: SizedBox(
              height: (valueSelected.ratingFeedback != noRate)
                  ? MediaQuery.of(context).size.height * 0.7
                  : MediaQuery.of(context).size.height * 0.5,
              width: widthScreen * widhtDialog,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                      height: MediaQuery.of(context).size.height * 0.1,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          GestureDetector(
                            onTap: () {
                              // setState(() {
                              //   rateValue = badRate;
                              // });
                              context
                                  .read<FeedbackSelect>()
                                  .select(valueSelected, badRate, '', '');
                            },
                            child: Container(
                              // color: Colors.red,
                              child: Image(
                                  width: widthScreen * widthEmoticon,
                                  height: widthScreen * heightEmoticon,
                                  fit: BoxFit.fill,
                                  image: AssetImage(
                                      (valueSelected.ratingFeedback == badRate)
                                          ? 'assets/emoji/bad.png'
                                          : 'assets/emoji/bad_grey.png')),
                              // width:
                              //     MediaQuery.of(context)
                              //             .size
                              //             .width *
                              //         widthEmoticon,
                            ),
                          ),
                          GestureDetector(
                            onTap: () {
                              // setState(() {
                              //   rateValue = neturalRate;
                              // });
                              context
                                  .read<FeedbackSelect>()
                                  .select(valueSelected, neutralRate, '', '');
                            },
                            child: Container(
                              // color: Colors.green,
                              child: Image(
                                  width: widthScreen * widthEmoticon,
                                  height: widthScreen * heightEmoticon,
                                  fit: BoxFit.fill,
                                  image: AssetImage(
                                      (valueSelected.ratingFeedback ==
                                              neutralRate)
                                          ? 'assets/emoji/neutral.png'
                                          : 'assets/emoji/neutral_grey.png')),
                              // width:
                              //     MediaQuery.of(context)
                              //             .size
                              //             .width *
                              //         widthEmoticon,
                            ),
                          ),
                          GestureDetector(
                            onTap: () {
                              // setState(() {
                              //   rateValue = goodRate;
                              // });
                              context
                                  .read<FeedbackSelect>()
                                  .select(valueSelected, goodRate, '', '');
                            },
                            child: Container(
                              // color: Colors.black,
                              child: Image(
                                  width: widthScreen * widthEmoticon,
                                  height: widthScreen * heightEmoticon,
                                  fit: BoxFit.fill,
                                  image: AssetImage(
                                      (valueSelected.ratingFeedback == goodRate)
                                          ? 'assets/emoji/good.png'
                                          : 'assets/emoji/good_grey.png')),
                              // width:
                              //     MediaQuery.of(context)
                              //             .size
                              //             .width *
                              //         widthEmoticon,
                            ),
                          )
                        ],
                      )),
                  SizedBox(height: MediaQuery.of(context).size.height * 0.03),
                  // for (int d = 0; d < feedBakcAnswer.length; d++)
                  (valueSelected.ratingFeedback != noRate)
                      ? Column(
                          children: [
                            // Text(
                            //   header,
                            //   textScaleFactor: textScaleFactor,
                            //   style: textStyleNormalFont(context),
                            // ),
                            defaultText(
                              context,
                              header,
                              style: textStyleNormalFont(context),
                            ),
                            SizedBox(
                                height:
                                    MediaQuery.of(context).size.height * 0.03),
                            Container(
                              height: MediaQuery.of(context).size.height * 0.2,
                              width: double.infinity,
                              // color: Colors.red,
                              child: ListView(
                                children: [
                                  Wrap(
                                    crossAxisAlignment:
                                        WrapCrossAlignment.start,
                                    alignment: WrapAlignment.start,
                                    spacing: 5,
                                    runSpacing: 5,
                                    children: [
                                      for (var feedback in feedBakcAnswer)
                                        GestureDetector(
                                          onTap: () {
                                            // setState(() {
                                            //   if (feedBakcAnswerSelected.contains(i)) {
                                            //     feedBakcAnswer.remove(i);
                                            //   } else {
                                            //     feedBakcAnswerSelected.add(i);
                                            //   }
                                            // });
                                            context
                                                .read<FeedbackSelect>()
                                                .select(
                                                    valueSelected,
                                                    valueSelected
                                                        .ratingFeedback,
                                                    feedback,
                                                    '');
                                          },
                                          child: Container(
                                            // padding: EdgeInsets.only(
                                            //   top: MediaQuery.of(context).size.height * 0.01,
                                            //   bottom: MediaQuery.of(context).size.height * 0.01,
                                            //   left: MediaQuery.of(context).size.width * 0.01,
                                            //   right: MediaQuery.of(context).size.width * 0.01,
                                            // ),
                                            padding: EdgeInsets.symmetric(
                                              vertical: widthScreen * 0.01,
                                              horizontal: widthScreen * 0.015,
                                            ),
                                            // height: MediaQuery.of(context).size.height * 0.04,
                                            decoration: BoxDecoration(
                                              borderRadius:
                                                  BorderRadius.circular(
                                                      roundedButton),
                                              color: (valueSelected.answerOption
                                                      .contains(feedback))
                                                  ? selectedColor
                                                  : buttonColor,
                                            ),
                                            child: Column(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.center,
                                              children: [
                                                // Text(i,
                                                //     textAlign: TextAlign.center,
                                                //     textScaleFactor:
                                                //         textScaleFactor,
                                                //     style: textStyleNormalFont(
                                                //       context,
                                                //       color: textInButton,
                                                //       font: normalFont,
                                                //       isBold: true,
                                                //     )),
                                                defaultText(context, feedback,
                                                    textAlign: TextAlign.center,
                                                    style: textStyleNormalFont(
                                                      context,
                                                      color: textInButton,
                                                      font: normalFont,
                                                      isBold: true,
                                                    ))
                                              ],
                                            ),
                                          ),
                                        ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ],
                        )
                      : const SizedBox(),
                  SizedBox(height: MediaQuery.of(context).size.height * 0.01),
                  TextField(
                    // autofocus: true,
                    keyboardType: TextInputType.text,
                    controller: rateNote,
                    maxLength: maxLengthTextField,
                    maxLines: 2,
                    // style: const TextStyle(
                    //   color: Colors.black,
                    //   fontSize: 18,
                    //   fontWeight: FontWeight.w400,
                    // ),
                    style: textStyleNormalFont(context),
                    decoration: InputDecoration(
                      // border: OutlineInputBorder(
                      //     borderRadius: BorderRadius.all(
                      //         Radius.circular(15))),
                      // border: InputBorder.none,
                      hintText: "Tuliskan pengalaman anda",
                      hintStyle: TextStyle(
                        color: Colors.grey,
                        fontSize:
                            MediaQuery.of(context).size.height * normalFont,
                      ),
                    ),
                  ),
                  SizedBox(height: MediaQuery.of(context).size.height * 0.01),
                  GestureDetector(
                    onTap: () async {
                      if (valueSelected.ratingFeedback == noRate) {
                        EasyLoading.showToast('Anda belum memilih rating');
                      } else {
                        Api.sendFeedBack(
                          valueSelected.ratingFeedback,
                          rateNote.text,
                          widget.bill.id,
                          valueSelected.answerOption,
                        ).then((value) {
                          Navigator.pop(context);
                          if (!widget.isHistory) {
                            context.read<ViewBillBloc>().getBill();
                          } else {
                            List<String> listHistory =
                                prefs.getStringList('list_history') ?? [];
                            if (listHistory.isNotEmpty) {
                              int indexHistory = listHistory.indexWhere(
                                (listHistory) =>
                                    jsonDecode(listHistory)['session'] ==
                                    widget.sessionId,
                              );
                              if (indexHistory != -1) {
                                dynamic jsonDecodeHistory =
                                    jsonDecode(listHistory[indexHistory]);
                                context.read<ViewBillBloc>().getBill(
                                      sessionIdH: jsonDecodeHistory['session'],
                                      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: MediaQuery.of(context).size.height * heightTombol,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(roundedButton),
                          color: buttonColor),
                      child: Align(
                        // child: Text(
                        //   'OK',
                        //   textScaleFactor: textScaleFactor,
                        //   // style: TextStyle(
                        //   //   fontWeight: FontWeight.w500,
                        //   //   fontSize:
                        //   //       MediaQuery.of(context).size.height * normalFont,
                        //   //   color: textInButton,
                        //   // ),
                        //   style: textStyleNormalFont(
                        //     context,
                        //     color: textInButton,
                        //   ),
                        // ),
                        child: defaultText(
                          context,
                          'OK',
                          style: textStyleNormalFont(
                            context,
                            color: textInButton,
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: MediaQuery.of(context).size.height * 0.02,
                  ),
                  GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                      // ontapCancel();
                    },
                    child: Container(
                      height: MediaQuery.of(context).size.height * heightTombol,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(roundedButton),
                        color: cancelColorButton,
                      ),
                      child: Align(
                          // child: Text(
                          //   'Batal',
                          //   textScaleFactor: textScaleFactor,
                          //   // style: TextStyle(
                          //   //   fontWeight: FontWeight.w500,
                          //   //   fontSize:
                          //   //       MediaQuery.of(context).size.height * normalFont,
                          //   //   color: textInButton,
                          //   // ),
                          //   style: textStyleNormalFont(
                          //     context,
                          //     color: textInButton,
                          //   ),
                          // ),
                          child: defaultText(context, 'Batal',
                              style: textStyleNormalFont(
                                context,
                                color: textCancelColor,
                              ))),
                    ),
                  )
                ],
              ),
            ),
          );
        },
      );
    });
  }
}
