import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';

class MobHistoryRatingPage extends StatefulWidget {
  final Map<String, dynamic> data;
  const MobHistoryRatingPage(this.data, {super.key});

  @override
  State<MobHistoryRatingPage> createState() => _MobHistoryRatingPageState();
}

class _MobHistoryRatingPageState extends State<MobHistoryRatingPage> {
  int tempRating = 0;
  String description = '';
  String ratingAspect = '';
  List aspectList = [];
  TextEditingController controllerOptOther = new TextEditingController();

  var rating = [
    {'key': 1, 'image': "assets/image/icon/very_dissatisfied.png", 'label': 'disatisfied'.tr()},
    {'key': 2, 'image': "assets/image/icon/dissatisfied.png", 'label': 'lessSatisfied'.tr()},
    {'key': 3, 'image': "assets/image/icon/neutral.png", 'label': 'satisfied'.tr()},
    {'key': 4, 'image': "assets/image/icon/satisfied.png", 'label': 'verySatisfied'.tr()},
    {'key': 5, 'image': "assets/image/icon/very_satisfied.png", 'label': 'reallyPleased'.tr()},
  ];

  getAspectList(){
    String locale = context.locale.toString();
    List optionList = widget.data['_ratingAspect'+locale[0].toUpperCase()+locale[1]] != null && widget.data['_ratingAspect'+locale[0].toUpperCase()+locale[1]].trim() != '' ? widget.data['_ratingAspect'+locale[0].toUpperCase()+locale[1]].split(';') : [];
    if(optionList.isNotEmpty){
      optionList.add('OTHER_OPTION');
    }
    else{
      ratingAspect = 'OTHER_OPTION';
    }

    setState(() {
      aspectList = optionList;
    });
  }

  @override
  Widget build(BuildContext context) {
    getAspectList();

    return Scaffold(
      backgroundColor: backgroundColor,
      appBar: PreferredSize(preferredSize: Size.fromHeight(0), child: AppBar(elevation: 0, backgroundColor: secondaryColor)),
      body: Column(
        children: [
          Container(
            width: double.infinity,
            padding: EdgeInsets.all(20),
            color: secondaryColor,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(widget.data[U.langColumn(context, 'requestSubject')], style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w600)),
                SizedBox(height: 4),
                Text(convertDate(widget.data['datetimeRequest'], context.locale.toString()), style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w300)),
              ],
            ),
          ),
          Expanded(
            child: Container(
              alignment: Alignment.topCenter,
              width: U.bodyWidth(context),
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                      padding: EdgeInsets.all(20),
                      child: Column(
                        children: [
                          Text('satisfactionAsk'.tr(), style: TextStyle(fontSize: 16)),
                          SizedBox(height: 12),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: List.generate(rating.length, (i) {
                              return Expanded(
                                child: GestureDetector(
                                  child: Image(
                                    image: AssetImage(rating[i]['image'].toString()),
                                    color: Colors.white.withValues(alpha: tempRating == rating[i]['key'] ? 1 : 0.3),
                                    colorBlendMode: BlendMode.modulate,
                                  ),
                                  onTap: () {
                                    setState(() {
                                      tempRating = rating[i]['key'] as int;
                                      description = rating[i]['label'] as String;
                                    });
                                  },
                                ),
                              );
                            }),
                          ),
                          SizedBox(height: 6),
                          Text(description, style: TextStyle(color: textColor, fontSize: 14, fontWeight: FontWeight.w300), textAlign: TextAlign.center),
                        ],
                      ),
                    ),
                    tempRating != 0 ? separator() : Container(),
                    tempRating != 0 ? Container(
                      padding: EdgeInsets.all(20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('whatMakesYou'.tr()+' '+description+'?', style: TextStyle(fontSize: 16)),
                          SizedBox(height: 12),
                          Wrap(
                            runSpacing: 10, spacing: 10,
                            children: List.generate(aspectList.length, (i){
                              return GestureDetector(
                                child: Container(
                                  padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                                  child: Text(aspectList[i]=='OTHER_OPTION'?'letMeWrite'.tr():aspectList[i], style: TextStyle(color: textColor)),
                                  decoration: BoxDecoration(
                                    color: aspectList[i] == ratingAspect ? primaryColor.withValues(alpha: 0.3) : Colors.white,
                                    border: Border.all(color: aspectList[i] == ratingAspect ? primaryColor : textColor),
                                    borderRadius: BorderRadius.all(Radius.circular(50))
                                  ),
                                ),
                                onTap: (){
                                  setState(() {
                                    ratingAspect = ratingAspect == aspectList[i]?'':aspectList[i];
                                  });
                                },
                              );
                            }),
                          ),
                          aspectList.isNotEmpty ? SizedBox(height: 10) : Container(),
                          ratingAspect == 'OTHER_OPTION' ? otherOptTextField() : Container(),
                        ],
                      ),
                    ) : Container(),
                    SizedBox(height: 10),
                    tempRating != 0 ? Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        SizedBox(width: 20),
                        Expanded(child: buttonTemplate(text: 'textCancel'.tr(), backgroundColor: Colors.black12, borderColor: Colors.black12, textColor: textColor, height: 40, action: (){
                          Navigator.of(context).pop();
                        })),
                        SizedBox(width: 20),
                        Expanded(child: buttonTemplate(text: 'save_rating'.tr(), backgroundColor: primaryColor, borderColor: primaryColor, height: 40, action: ()async{
                          showLoading(context);
                          var data = {"ticketNo": widget.data['ticketNo'], "rateSatisfy": tempRating};
                          if(ratingAspect != 'OTHER_OPTION'){
                            data['aspect'] = ratingAspect;
                          }
                          else if(ratingAspect == 'OTHER_OPTION' && controllerOptOther.text.isNotEmpty){
                            data['aspect'] = controllerOptOther.text;
                          }

                          var res = await ApiAuthProvider() .postData('/api/requestHistories/rateSatisfy', null, data, context);
                          closeLoading(context);
                          if (res != null) {
                            Navigator.of(context).pop(tempRating);
                          }
                        })),
                        SizedBox(width: 20),
                      ],
                    ) : Container()
                  ],
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  otherOptTextField(){
    return TextFormField(
      maxLines: 1, maxLength: 50,
      controller: controllerOptOther,
      style: TextStyle(fontSize: 14, color: Colors.black),
      decoration: InputDecoration(
        counterText: '',
        counterStyle: TextStyle(fontSize: 0),
        hintText: 'writeHere'.tr(),
        hintStyle: TextStyle(color: textColor.withValues(alpha: 0.5), fontSize: 14),
        filled: true, fillColor: Colors.white,
        isDense: true,
        contentPadding: EdgeInsets.all(13),
        prefixIcon: Padding(padding: EdgeInsets.only(left: 13, right: 13), child: U.iconsax('edit-2', color: textColor, size: 22)),
        enabledBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: Color(0xff262626).withValues(alpha: 0.5))),
        focusedBorder: OutlineInputBorder(borderRadius: BorderRadius.circular(12), borderSide: BorderSide(color: primaryColor)),
      ),
    );
  }
}
