import 'package:easy_localization/easy_localization.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:lazy_load_scrollview/lazy_load_scrollview.dart';
import 'package:provider/provider.dart';
import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
import 'package:telnow_mobile_new/src/layouts/functions/history.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/history_detail.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/history_detail_pending.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/history_rating.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:telnow_mobile_new/src/utils/dio_logging_interceptors.dart';
import 'package:telnow_mobile_new/src/utils/provider.dart';

class MobHistoryPage extends StatefulWidget {
  const MobHistoryPage({super.key});

  @override
  State<MobHistoryPage> createState() => _MobHistoryPageState();
}

class _MobHistoryPageState extends State<MobHistoryPage> with TickerProviderStateMixin {
  final HistoryFunction historyFunction = HistoryFunction();
  late AnimationController _animationController;
  late final HistoryModule historyModule;
  late final UserModule userModule;
  final List<String> pages = ['ongoing::none', 'ongoing::queue', 'ongoing::done', 'ongoing::hold', 'done::none', 'done::finish', 'done::cancel'];

  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()},
  ];
  bool _timeLimit = false;

  @override
  void initState() {
    historyModule = Provider.of<HistoryModule>(context, listen: false);
    userModule = Provider.of<UserModule>(context, listen: false);
    historyModule.reset();
    _animationController = AnimationController(vsync: this, duration: Duration(seconds: 1));
    _animationController.repeat(reverse: true);
    initializePages();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      historyFunction.getActiveForum();
      // getUser taruh sini dulu. di-load bareng render widget. 031125
      historyFunction.getUser();
      historyModule.setCurrentPage();
      historyFunction.getMission();
    });
    // TODO: implement initState
    super.initState();
  }

  void initializePages(){
    Map<String, List> data = {};
    Map<String, bool> isLoad = {};

    for(var i=0; i<pages.length; i++){
      // debugPrint('initialize for ${pages[i]}, length: ${pages.length}');
      data[pages[i]] = [];
      isLoad[pages[i]] = false;
    }
    historyModule.initDataPages(data);
    historyModule.initIsLoadPages(isLoad);
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final historyModuleListen = Provider.of<HistoryModule>(context);
    final userModuleListen = Provider.of<UserModule>(context);
    eventBus.on().listen((event){
      debugPrint(event.toString());
    });
    return userModuleListen.resetData() ? RefreshPage(() {
      userModule.setResetData(false);
      historyFunction.getActiveForum();
    }) : _timeLimit ? showButton(context) : Scaffold(
      backgroundColor: backgroundColor,
      appBar: AppBar(
        elevation: 0,
        bottomOpacity: 0,
        backgroundColor: backgroundColor,
        titleSpacing: 16,
        title: Text('history'.tr(), style: TextStyle(color: textColor, fontSize: 17, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
        actions: [
          if(historyModuleListen.multiSelectMode()) Center(
            child: GestureDetector(
              child: Container(
                margin: EdgeInsets.only(right: 16),
                padding: EdgeInsets.fromLTRB(16, 9, 16, 9),
                decoration: BoxDecoration(
                    color: primaryColor.withValues(alpha: 0.1), border: Border.all(color: primaryColor), borderRadius: BorderRadius.all(Radius.circular(50))),
                child: Row(
                  children: [
                    Text('delete'.tr(), style: TextStyle(color: primaryColor, fontSize: 14)),
                    SizedBox(width: 5),
                    U.iconsax('trash', color: primaryColor, size: 20)
                  ],
                ),
              ),
              onTap: () => historyFunction.deleteData(context),
            ),
          )
        ],
      ),
      body: Column(
        children: [
          divider(),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: 16),
              buildTab(historyModuleListen),
              SizedBox(height: 20),
              buildFilter(historyModuleListen),
              // historyModuleListen.activeTab() == 0 ? doneFilter() : ongoingFilter(),
              SizedBox(height: 20),
            ],
          ),
          Expanded(
            child: userModuleListen.user().isNotEmpty
                ? indexedStackedBody()
                : userModuleListen.resetData()
                ? Container()
                : loadingTemplate(() {
                    if(mounted) setState(() => _timeLimit=true);
                  },
            ),
          )
        ],
      ),
    );
  }

  //# kodingan baru start
  Widget buildTab(historyModuleListen){
    HistoryTab activeTab = historyModuleListen.activeTab();

    return Row(
      children: [
        GestureDetector(
          child: Container(
            margin: EdgeInsets.only(left: 16),
            padding: EdgeInsets.symmetric(vertical: 5, horizontal: 16),
            decoration: BoxDecoration(
                color: Colors.white,
                border: Border(bottom: BorderSide(color: activeTab.name == "ongoing" ? primaryColor : primaryColor.withValues(alpha: 0.3), width: activeTab.name == "ongoing" ? 2 : 1))),
            child: Text('ongoing'.tr(), style: TextStyle(color: activeTab.name == "ongoing" ? textColor : textColor.withValues(alpha: 0.65), fontSize: 16)),
          ),
          onTap: () {
            // if (!historyModule.isLoadHistory()) {
              historyModule.setSelectedFilter('none');
              historyModule.setActiveTab(HistoryTab.ongoing);
              historyFunction.onRefresh();
            // }
          },
        ),
        GestureDetector(
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 5, horizontal: 16),
            decoration: BoxDecoration(color: Colors.white, border: Border(bottom: BorderSide(color: activeTab.name == "done" ? primaryColor : primaryColor.withValues(alpha: 0.3), width: activeTab.name == "done" ? 2 : 1))),
            child: Text('done'.tr(), style: TextStyle(color: activeTab.name == "done" ? textColor : textColor.withValues(alpha: 0.65), fontSize: 16)),
          ),
          onTap: () {
            // if (!historyModule.isLoadHistory()) {
              historyModule.setSelectedFilter('none');
              historyModule.setActiveTab(HistoryTab.done);
              historyFunction.onRefresh();
            // }
          },
        ),
      ],
    );
  }

  Widget buildFilter(historyModuleListen){
    HistoryTab tab = historyModuleListen.activeTab();
    List currentFilters = tab.filters;

    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: List.generate(currentFilters.length, (i) {
          return GestureDetector(
            child: Container(
              margin: EdgeInsets.only(left: 16),
              padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
              decoration: BoxDecoration(
                  color: historyModuleListen.checkSelectedFilter(currentFilters[i]['value']) ? primaryColor : Color(0xffF2F8F7),
                  border: Border.all(color: historyModuleListen.checkSelectedFilter(currentFilters[i]['value']) ? primaryColor : Color(0xffBEC1C1)),
                  borderRadius: BorderRadius.all(Radius.circular(50))),
              child: Text(currentFilters[i]['title'], style: TextStyle(color: historyModuleListen.checkSelectedFilter(currentFilters[i]['value']) ? Colors.white : textColor, fontSize: 16)),
            ),
            onTap: () {
              // if (!historyModule.isLoadHistory()) {
                if (historyModule.checkSelectedFilter(currentFilters[i]['value'])) {
                  historyModule.setSelectedFilter('none');
                  historyFunction.onRefresh();
                } else {
                  historyModule.setSelectedFilter(currentFilters[i]['value']);
                  historyFunction.onRefresh();
                }
              // }
            },
          );
        }),
      ),
    );
  }

  Widget indexedStackedBody(){
    HistoryModule historyModuleListen = Provider.of<HistoryModule>(context);
    int currentIndex = pages.indexOf(historyModuleListen.currentPage());
// debugPrint('current index: $currentIndex for ${historyModuleListen.currentPage()}');

    return IndexedStack(
      index: currentIndex,
      children: List.generate(pages.length, (i){
        return buildBody(pages[i]);
      }),
    );
  }

  Widget buildBody(String keyState){
    HistoryModule historyModuleListen = Provider.of<HistoryModule>(context);
    // debugPrint('build for $keyState. The data is ${historyModuleListen.dataRequests(state: keyState).length}');

    return Container(
      alignment: Alignment.topCenter,
      width: U.bodyWidth(context),
      child: LazyLoadScrollView(
        onEndOfPage: () => historyFunction.getMission(),
        scrollOffset: 500,
        child: EasyRefresh(
          header: MaterialHeader(clamping: true, color: primaryColor),
          onRefresh: () => historyFunction.onRefresh(),
          child: keyState.startsWith('done',0) ? doneContainer(historyModuleListen, keyState) : ongoingContainer(historyModuleListen, keyState),
        ),
      ),
    );
  }
  //# kodingan baru end

  Widget ongoingContainer(HistoryModule historyModuleListen, String state) {
    // final HistoryModule historyModuleListen = Provider.of<HistoryModule>(context);
    final dataPending = historyModuleListen.dataPending();
    final dataRequest = historyModuleListen.dataRequests(state: state);

    return SingleChildScrollView(
      child: Column(
        children: [
          !U.getInternetStatus() ? Column(
            children: List.generate(dataPending.length, (i) {
              return GestureDetector(
                child: Container(
                  padding: EdgeInsets.all(16),
                  decoration: BoxDecoration(color: Colors.white, border: Border(bottom: BorderSide(color: Color(0xffF3F3F3), width: 8))),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          imageTiles(imageUrl: dataPending[i]['image'] ?? "null"),
                          SizedBox(width: 16),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(dataPending[i]['title'], style: TextStyle(color: textColor, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
                                SizedBox(height: 6),
                                Text(dataPending[i][U.langColumn(context, 'sub')], style: TextStyle(color: textColor), overflow: TextOverflow.ellipsis),
                                SizedBox(height: 6),
                                Text(convertDate(dataPending[i]['datetimeRequest'], context.locale.toString()), style: TextStyle(color: textColor, fontSize: 13, fontWeight: FontWeight.w300)),
                              ],
                            ),
                          )
                        ],
                      ),
                      SizedBox(height: 16),
                      divider(),
                      Container(
                        width: double.infinity,
                        margin: EdgeInsets.only(top: 16),
                        child: Row(
                          children: [
                            Container(
                              width: 25, height: 25,
                              decoration: BoxDecoration(image: DecorationImage(image: AssetImage('assets/image/general/Hourglass.png'), fit: BoxFit.cover)),
                            ),
                            SizedBox(width: 8),
                            Expanded(child: Text('pending_info_tiles'.tr(), style: TextStyle(color: textColor, fontSize: 14), overflow: TextOverflow.ellipsis))
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                onTap: () {
                  if(!U.getInternetStatus()){
                    navigateTo(context, MobHistoryDetailPendingPage(data: historyModule.dataPending()[i])).then((val) {
                      val = val??false;
                      if(val) historyFunction.onRefresh();
                    });
                  }
                  else{
                    historyFunction.onRefresh();
                  }
                },
              );
            }),
          ) : Container(),

          Column(
            children: List.generate(dataRequest.length, (i) {
              return GestureDetector(
                child: Container(
                  padding: EdgeInsets.all(16),
                  decoration: BoxDecoration(color: Colors.white, border: Border(bottom: BorderSide(color: Color(0xffF3F3F3), width: 8))),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          imageTiles(imageUrl: dataRequest[i]['_requestImage'] ?? "null"),
                          SizedBox(width: 16),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(dataRequest[i][U.langColumn(context, 'requestGroupDescription')]??'', style: TextStyle(color: textColor, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
                                SizedBox(height: 6),
                                Text(dataRequest[i][U.langColumn(context, 'requestSubject')]??'', style: TextStyle(color: textColor), overflow: TextOverflow.ellipsis),
                                SizedBox(height: 6),
                                renderRequested(dataRequest[i]),
                                Text(convertDate(dataRequest[i]['datetimeRequest']??'', context.locale.toString()), style: TextStyle(color: textColor, fontSize: 13, fontWeight: FontWeight.w300)),
                              ],
                            ),
                          )
                        ],
                      ),
                      dataRequest[i]['currentState'] == 'DIMULAI' || dataRequest[i]['_hasForum'] ? Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(height: 16),
                          divider(),
                        ],
                      ) : Container(),
                      dataRequest[i]['_activeHoldRequest'] != null ? Container(
                        width: double.infinity,
                        margin: EdgeInsets.only(top: 16),
                        child: Row(
                          children: [
                            Container(
                              width: 25, height: 25,
                              decoration: BoxDecoration(image: DecorationImage(image: AssetImage('assets/image/general/Watch.png'), fit: BoxFit.cover)),
                            ),
                            SizedBox(width: 8),
                            Expanded(child: Text(dataRequest[i]['_activeHoldRequest']['description'], style: TextStyle(color: textColor, fontSize: 14), overflow: TextOverflow.ellipsis))
                          ],
                        ),
                      ) : dataRequest[i]['currentState'] == 'DIMULAI' ? Container(
                        width: double.infinity,
                        margin: EdgeInsets.only(top: 16),
                        child: Row(
                          children: [
                            Container(
                              width: 25, height: 25,
                              decoration: BoxDecoration(
                                  border: Border.all(color: primaryColor),
                                  borderRadius: BorderRadius.all(Radius.circular(25)),
                                  image: DecorationImage(image: AssetImage('assets/image/general/Avatar.jpg'), fit: BoxFit.cover)),
                            ),
                            SizedBox(width: 8),
                            Expanded(child: Text(dataRequest[i]['servantNameStart'] + 'isWorking'.tr(), style: TextStyle(color: textColor, fontSize: 14), overflow: TextOverflow.ellipsis))
                          ],
                        ),
                      ) : Container(),
                      !dataRequest[i]['autoResponse'] && dataRequest[i]['_hasForum'] && dataRequest[i]['_forumMsg'] != null ? Container(
                        width: double.infinity,
                        margin: EdgeInsets.only(top: 16),
                        child: Row(
                          children: [
                            FadeTransition(opacity: _animationController, child: U.iconsax('messages-3', color: primaryColor)),
                            SizedBox(width: 8),
                            Expanded(child: Text('“${dataRequest[i]['_forumMsg']}”', style: TextStyle(color: textColor.withValues(alpha: 0.75), fontSize: 14, fontStyle: FontStyle.italic), overflow: TextOverflow.ellipsis,))
                          ],
                        ),
                      )
                          : Container(),
                    ],
                  ),
                ),
                onTap: () => navigateTo(context, MobHistoryDetailPage(index: i)).then((val) {
                  val = val??false;
                  if(val) historyModule.cancelMisi(i);
                }),
              );
            }),
          ),
          !historyModuleListen.stopLoadHistory() || (historyModuleListen.isLoadHistory() && historyModuleListen.page() > 0)
              ? Container(margin: EdgeInsets.only(top: historyModuleListen.page() > 0 ? 0 : 50), child: loadingTemplateNoVoid())
              : dataRequest.isEmpty && dataPending.isEmpty
              ? NoDataPage()
              : Container(),
        ],
      ),
    );
  }

  Widget doneContainer(HistoryModule historyModuleListen, String state) {
    // final HistoryModule historyModuleListen = Provider.of<HistoryModule>(context);
    final dataRequest = historyModuleListen.dataRequests(state: state);

    return SingleChildScrollView(
      child: Column(
        children: [
          Column(
              children: List.generate(dataRequest.length, (i) {
                return GestureDetector(
                  child: Container(
                    padding: EdgeInsets.all(16),
                    decoration: BoxDecoration(
                        color: historyModuleListen.selectedIndexes().contains(i) ? primaryColor.withValues(alpha: 0.05) : Colors.white,
                        border: Border(bottom: BorderSide(color: Color(0xffF3F3F3), width: 8))),
                    child: Column(
                      children: [
                        Row(
                          // crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            imageTiles(imageUrl: dataRequest[i]['_requestImage'] ?? "null"),
                            SizedBox(width: 16),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(dataRequest[i][U.langColumn(context, 'requestGroupDescription')]??"",
                                      style: TextStyle(color: textColor, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
                                  SizedBox(height: 6),
                                  Text(dataRequest[i][U.langColumn(context, 'requestSubject')]??"", style: TextStyle(color: textColor), overflow: TextOverflow.ellipsis),
                                  SizedBox(height: 6),
                                  renderRequested(dataRequest[i]),
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text(convertDate(dataRequest[i]['datetimeRequest'], context.locale.toString()),
                                          style: TextStyle(color: textColor, fontSize: 13, fontWeight: FontWeight.w300)),
                                      Text(
                                          ' - ${dataRequest[i]['currentState'] == 'DISELESAIKAN' || dataRequest[i]['currentState'] == 'TUNTAS' ? 'stateFinish'.tr() : 'stateCancel'.tr()}',
                                          style: TextStyle(
                                              color: dataRequest[i]['currentState'] == 'DISELESAIKAN' ||
                                                  dataRequest[i]['currentState'] == 'TUNTAS'
                                                  ? primaryColor
                                                  : Color(0xffD81010),
                                              fontSize: 13,
                                              fontWeight: FontWeight.w300))
                                    ],
                                  )
                                ],
                              ),
                            )
                          ],
                        ),
                        SizedBox(height: 16),
                        divider(),
                        SizedBox(height: 16),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            !dataRequest[i]['autoResponse'] && dataRequest[i]['servantIdentityStart'] != '#system' && (dataRequest[i]['currentState'] == 'TUNTAS' || dataRequest[i]['currentState'] == 'DISELESAIKAN') ? Container(
                              child: historyFunction.askForRate(dataRequest[i]) ? GestureDetector(
                                child: Container(
                                  padding: EdgeInsets.symmetric(vertical: 4, horizontal: 16),
                                  decoration: BoxDecoration(
                                      color: Colors.white,
                                      border: Border.all(color: secondaryColor),
                                      borderRadius: BorderRadius.all(Radius.circular(50))),
                                  child: Text('rateReq'.tr(), style: TextStyle(color: secondaryColor, fontSize: 14), overflow: TextOverflow.ellipsis),
                                ),
                                onTap: () {
                                  navigateTo(context, MobHistoryRatingPage(historyModule.dataRequests()[i])).then((tempRating) {
                                    if(tempRating != null){
                                      historyModule.setSatisfaction(i, tempRating);
                                    }
                                  });
                                },
                              ) : !historyFunction.isAutoResponse(dataRequest[i]) ? Row(
                                children: [
                                  Image(image: AssetImage(rating[dataRequest[i]['satisfactionRate'] - 1]['image'].toString()), width: 25),
                                  SizedBox(width: 5),
                                  Text(rating[dataRequest[i]['satisfactionRate'] - 1]['label'].toString(), style: TextStyle(color: textColor, fontSize: 14), overflow: TextOverflow.ellipsis),
                                ],
                              ) : Container(),
                            ) : message(dataRequest[i]['_hasForum'], dataRequest[i]['_forumMsg'] ?? "null"),
                            GestureDetector(
                              child: Container(
                                padding: EdgeInsets.symmetric(vertical: 4, horizontal: 16),
                                decoration: BoxDecoration(color: Colors.white, border: Border.all(color: primaryColor), borderRadius: BorderRadius.all(Radius.circular(50))),
                                child: Text('reqAgain'.tr(), style: TextStyle(color: primaryColor, fontSize: 14)),
                              ),
                              onTap: () => historyFunction.requestAgainAction(i),
                            )
                          ],
                        ),
                        (!dataRequest[i]['autoResponse'] && dataRequest[i]['servantIdentityStart'] != '#system' && (dataRequest[i]['currentState'] == 'TUNTAS' || dataRequest[i]['currentState'] == 'DISELESAIKAN')) ? message(dataRequest[i]['_hasForum'], dataRequest[i]['_forumMsg'] ?? "null", top: 16) : Container()
                      ],
                    ),
                  ),
                  onTap: () {
                    if (historyModule.multiSelectMode()) {
                      historyFunction.selectedController(context, i);
                    } else {
                      navigateTo(context, MobHistoryDetailPage(index: i));
                    }
                  },
                  onLongPress: () => historyFunction.selectedController(context, i),
                );
              })),
          !historyModuleListen.stopLoadHistory() || (historyModuleListen.isLoadHistory() && historyModuleListen.page() > 0)
              ? Container(margin: EdgeInsets.only(top: historyModuleListen.page() > 0 ? 0 : 50), child: loadingTemplateNoVoid())
              : dataRequest.isEmpty
              ? NoDataPage()
              : Container(),
        ],
      ),
    );
  }

  Widget renderRequested(list){
    if(list['receptionistId'] != null){
      var user = userModule.user();
      if(user['roomAttendant'] && user['userId'] != list['informantUserId'] && user['userId'] == list['receptionistId']){
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('${'requestedFor'.tr()}: ${list['informantName']??'-'}' ,style: TextStyle(color: textColor, fontSize: 13, fontWeight: FontWeight.w300)),
            SizedBox(height: 6),
          ],
        );
      }

      if(user['userId'] == list['informantUserId'] && user['userId'] != list['receptionistId']){
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('${'requestedBy'.tr()}: ${list['receptionistName']??''}' ,style: TextStyle(color: textColor, fontSize: 13, fontWeight: FontWeight.w300)),
            SizedBox(height: 6),
          ],
        );
      }
    }

    return Container();
  }

  Widget message(bool _hasForum, String _forumMsg, {double top = 0}) {
    return _hasForum ? Container(
      margin: EdgeInsets.only(top: top),
      child: Row(
        children: [
          FadeTransition(opacity: _animationController, child: U.iconsax('messages-3', color: primaryColor)),
          SizedBox(width: 8),
          Text('“$_forumMsg”',
              style: TextStyle(color: textColor.withValues(alpha: 0.75), fontSize: 14, fontStyle: FontStyle.italic),
              overflow: TextOverflow.ellipsis),
        ],
      ),
    ) : Container();
  }

  rateMission(BuildContext context, list, index) {
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        isScrollControlled: true,
        builder: (contexts) {
          int tempRating = 0;
          String description = '';
          return StatefulBuilder(
            builder: (contextt, setStates) {
              return Container(
                decoration: BoxDecoration(color: secondaryColor, borderRadius: BorderRadius.only(topLeft: Radius.circular(24), topRight: Radius.circular(24))),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: EdgeInsets.symmetric(vertical: 12, horizontal: 16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(list[U.langColumn(context, 'requestSubject')], style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w600)),
                          SizedBox(height: 4),
                          Text(convertDate(list['datetimeRequest'], context.locale.toString()), style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w300)),
                        ],
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.fromLTRB(30, 0, 30, 16),
                      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.only(topLeft: Radius.circular(24), topRight: Radius.circular(24))),
                      child: Column(
                        children: [
                          Container(
                            margin: EdgeInsets.all(10),
                            width: 40,
                            height: 4,
                            decoration: BoxDecoration(color: Color(0xff292D32).withValues(alpha: 0.2), borderRadius: BorderRadius.all(Radius.circular(10))),
                          ),
                          SizedBox(height: 12),
                          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,
                                  ),
                                  // child: Icon(rating[i]['icon'] as IconData, color: tempRating == rating[i]['key']?rating[i]['color'] as Color:Colors.grey),
                                  onTap: () {
                                    setStates(() {
                                      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),
                          SizedBox(height: 10),
                          Opacity(
                            opacity: tempRating > 0 ? 1 : 0,
                            child: buttonTemplate(text: 'save_rating'.tr(), backgroundColor: secondaryColor, borderColor: secondaryColor, height: 40, action: ()async{
                              if (tempRating > 0) {
                                var data = {"ticketNo": list['ticketNo'], "rateSatisfy": tempRating};

                                var res = await ApiAuthProvider() .postData('/api/requestHistories/rateSatisfy', null, data);
                                if (res != null) {
                                  historyModule.setSatisfaction(index, tempRating);
                                  navigateBack(contexts);
                                }
                              }
                            }),
                          )
                        ],
                      ),
                    )
                  ],
                ),
              );
            },
          );
        });
  }
}
