import 'dart:convert';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:mohem_flutter_app/api/dashboard_api_client.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/config/routes.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/models/itg/itg_main_response.dart';
import 'package:mohem_flutter_app/models/itg/itg_response_model.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';
import 'package:mohem_flutter_app/widgets/dynamic_forms/dynamic_textfield_widget.dart';

class SurveyScreen extends StatefulWidget {
  const SurveyScreen({Key? key}) : super(key: key);

  @override
  _SurveyScreenState createState() => _SurveyScreenState();
}

class _SurveyScreenState extends State<SurveyScreen> {
  String reviewText = "";
  double starRating = 1;
  int _selectedIndex = 5;

  ItgResponseData? itgResponseData;

  @override
  Widget build(BuildContext context) {
    if (itgResponseData == null) itgResponseData = ModalRoute.of(context)!.settings.arguments as ItgResponseData;
    return Scaffold(
        backgroundColor: MyColors.backgroundColor,
        body: Column(
          children: [
            Expanded(
                child: ListView(
              scrollDirection: Axis.vertical,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    124.height,
                    LocaleKeys.feedbackUserExperience.tr().toText19(),
                    27.height,
                    LocaleKeys.rateUI.tr().toText16(),
                    22.height,
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        RatingBar.builder(
                          initialRating: 3,
                          minRating: starRating,
                          direction: Axis.horizontal,
                          allowHalfRating: false,
                          itemCount: 5,
                          itemPadding: EdgeInsets.symmetric(horizontal: 8),
                          itemBuilder: (context, _) => Icon(
                            Icons.star,
                            color: Colors.amber,
                          ),
                          onRatingUpdate: (rating) {
                            starRating = rating;
                          },
                        )
                      ],
                    ).paddingOnly(left: 22, right: 22, top: 12, bottom: 12).objectContainerView(disablePadding: true),
                    39.height,
                    LocaleKeys.rateUI.tr().toText16(),
                    10.height,
                    GridView(
                      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 5, crossAxisSpacing: 7, mainAxisSpacing: 7),
                      physics: const NeverScrollableScrollPhysics(),
                      padding: const EdgeInsets.only(top: 0),
                      shrinkWrap: true,
                      children: [
                        optionUI("poor.svg", 1),
                        optionUI("bad.svg", 2),
                        optionUI("normal.svg", 3),
                        optionUI("good.svg", 4),
                        optionUI("xcellent.svg", 5),
                      ],
                    ),
                    27.height,
                    DynamicTextFieldWidget(
                      LocaleKeys.description.tr(),
                      LocaleKeys.typeHere.tr(),
                      lines: 3,
                      onChange: (v) {
                        reviewText = v;
                      },
                    ),
                    150.height
                  ],
                ).paddingOnly(left: 21, right: 21),
              ],
            )),
            DefaultButton(
              LocaleKeys.submitSurvey.tr(),
              () {
                performAPI();
              },
            ).insideContainer,
          ],
        ));
  }

  Widget optionUI(String icon, int index) {
    return (_selectedIndex == index
            ? SvgPicture.asset(
                'assets/images/' + icon,
                height: 32,
                width: 32,
              ).objectContainerBorderView(disablePadding: true, borderColor: MyColors.textMixColor, disableWidth: true, isAlignment: true)
            : SvgPicture.asset(
                'assets/images/' + icon,
                height: 32,
                width: 32,
              ).objectContainerView(
                disablePadding: true,
              ))
        .onPress(() {
      _selectedIndex = index;
      setState(() {});
    });
  }

  void performAPI() async {
    Utils.showLoading(context);
    try {
      ItgMainRes? res= await DashboardApiClient().submitItgForm(
          comment: reviewText,
          masterId: itgResponseData!.notificationMasterId ?? "",
          itgList: [
            {"questionId": "1", "optionId": null, "starRating": starRating},
            {"questionId": "2", "optionId": "4", "starRating": _selectedIndex}
          ],
          serviceId: itgResponseData!.serviceId ?? 0);
      Utils.hideLoading(context);


      
      if(res!.mohemmItgResponseItem!.statusCode==200){
        Utils.showToast("Survey has been submitted successfully");
        Navigator.pop(context);
      }else{
        Utils.showToast(res.mohemmItgResponseItem!.message.toString());
      }
   
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, (msg) {
        Utils.confirmDialog(context, msg);
      });
    }
  }
}
