import 'package:hmg_patient_app/core/model/ask_doctor/DoctorResponse.dart';
import 'package:hmg_patient_app/core/service/medical/ask_doctor_services.dart';
import 'package:hmg_patient_app/core/viewModels/medical/ask_doctor_view_model.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/pages/base/base_view.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';
import 'package:hmg_patient_app/uitl/date_uitl.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/widgets/buttons/defaultButton.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';

class ViewDoctorResponsesPage extends StatefulWidget {
  final DoctorResponse? doctorResponse;

  const ViewDoctorResponsesPage({Key? key, this.doctorResponse}) : super(key: key);

  @override
  State<ViewDoctorResponsesPage> createState() => _ViewDoctorResponsesPageState();
}

class _ViewDoctorResponsesPageState extends State<ViewDoctorResponsesPage> {
  int rate = 1;
  TextEditingController textController = new TextEditingController();
  late ProjectViewModel projectViewModel;

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    return BaseView<AskDoctorViewModel>(
      onModelReady: (model) => model.updateReadStatus(transactionNo: widget.doctorResponse!.transactionNo!),
      builder: (_, model, w) => AppScaffold(
        isShowAppBar: true,
        showNewAppBar: true,
        showNewAppBarTitle: true,
        backgroundColor: Color(0xffF8F8F8),
        isShowDecPage: false,
        appBarTitle: TranslationBase.of(context).viewDoctorResponses,
        baseViewModel: model,
        body: SingleChildScrollView(
          child: Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [getResponsesList()],
            ),
          ),
        ),
      ),
    );
  }

  Widget getResponsesList() {
    return ListView.separated(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        padding: EdgeInsets.only(bottom: 14, top: 14, left: 21, right: 21),
        itemBuilder: (context, _index) {
          return Container(
            padding: const EdgeInsets.only(left: 20, right: 12, top: 12, bottom: 12),
            height: 160,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(
                  Radius.circular(10.0),
                ),
                border: Border.all(width: 1, color: Color(0xffEFEFEF)),
                boxShadow: [
                  BoxShadow(
                    color: Color(0xff000000).withOpacity(.05),
                    //spreadRadius: 5,
                    blurRadius: 27,
                    offset: Offset(0, -3),
                  ),
                ],
                color: Colors.white),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  child: Text(
                    (widget.doctorResponse!.doctorName ?? ""),
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: Color(0xff2E303A),
                      letterSpacing: -0.64,
                    ),
                  ),
                ),
                Container(
                  child: Text(
                    (DateUtil.getDayMonthYearDateFormatted(DateUtil.convertStringToDate(widget.doctorResponse!.createdOn!)) ?? ""),
                    style: TextStyle(
                      fontSize: 14,
                      color: Color(0xff2E303A),
                      letterSpacing: -0.64,
                    ),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 10.0),
                  child: Text(
                    widget.doctorResponse!.transactions![_index]['DoctorResponse'],
                    style: TextStyle(
                      fontSize: 16,
                      color: Color(0xff2E303A),
                      letterSpacing: -0.64,
                    ),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 10.0),
                  child: DefaultButton(
                    TranslationBase.of(context).rateDoctorResponse,
                    () {
                      openResponseRateDialog(context);
                    },
                    color: CustomColors.accentColor,
                  ),
                ),
              ],
            ),
          );
        },
        separatorBuilder: (context, index) => SizedBox(height: 14),
        itemCount: widget.doctorResponse!.transactions!.length);
  }

  void openResponseRateDialog(BuildContext context) {
    showModalBottomSheet(
        context: context,
        enableDrag: true,
        isDismissible: true,
        isScrollControlled: true,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(topLeft: Radius.circular(12), topRight: Radius.circular(12)),
        ),
        backgroundColor: Colors.white,
        builder: (context) {
          return StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
            return Container(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  SizedBox(
                    height: 16.0,
                  ),
                  Text(
                    TranslationBase.of(context).rateDoctorResponseHeading,
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.w600,
                      color: Color(0xff2E303A),
                      letterSpacing: -0.64,
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(24.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Container(
                          margin: rate == 1 ? EdgeInsets.only(left: 3.0, right: 3.0) : EdgeInsets.only(left: 0.0, right: 0.0),
                          decoration: rate == 1
                              ? BoxDecoration(borderRadius: BorderRadius.circular(100), border: Border.all(width: 3, color: CustomColors.green))
                              : BoxDecoration(borderRadius: BorderRadius.circular(100), border: Border.all(width: 3, color: CustomColors.white)),
                          child: IconButton(
                            onPressed: () {
                              rate = 1;
                              setState(() {});
                            },
                            iconSize: 35,
                            icon: SvgPicture.asset('assets/images/new/appointment-rating/5.svg'),
                          ),
                        ),
                        Container(
                          margin: rate == 0 ? EdgeInsets.only(left: 3.0, right: 3.0) : EdgeInsets.only(left: 0.0, right: 0.0),
                          decoration: rate == 0
                              ? BoxDecoration(borderRadius: BorderRadius.circular(100), border: Border.all(width: 3, color: CustomColors.green))
                              : BoxDecoration(borderRadius: BorderRadius.circular(100), border: Border.all(width: 3, color: CustomColors.white)),
                          child: IconButton(
                            onPressed: () {
                              rate = 0;
                              setState(() {});
                            },
                            iconSize: 35,
                            icon: SvgPicture.asset('assets/images/new/appointment-rating/1.svg'),
                          ),
                        ),
                      ],
                    ),
                  ),
                  if (rate == 0)
                    Container(
                      padding: const EdgeInsets.all(24.0),
                      child: Padding(
                        padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
                        child: inputWidget(TranslationBase.of(context).comments, "", textController, isEnable: true),
                      ),
                    ),
                  SizedBox(
                    height: 16.0,
                  ),
                  Container(
                    margin: EdgeInsets.fromLTRB(24.0, 0.0, 24.0, 24.0),
                    child: DefaultButton(
                      TranslationBase.of(context).submit,
                      () {
                        if (rate == 0 && textController.text.isEmpty) {
                          AppToast.showErrorToast(message: "Please enter comments");
                        } else {
                          rateDoctorResponse();
                        }
                      },
                      color: CustomColors.accentColor,
                    ),
                  ),
                ],
              ),
            );
          });
        }).then((value) {
      rate = 1;
      setState(() {});
    });
  }

  void rateDoctorResponse() {
    GifLoaderDialogUtils.showMyDialog(context);
    AskDoctorService service = new AskDoctorService();
    service
        .rateDoctorResponse(
            transactionNo: widget.doctorResponse!.transactionNo!,
            questionType: widget.doctorResponse!.requestType!,
            rate: rate,
            notes: textController.text,
            mobileNo: projectViewModel.user!.mobileNumber!,
            idNo: projectViewModel.user!.patientIdentificationNo!,
            patientName: projectViewModel.user!.firstName! + " " + projectViewModel.user!.lastName!,
            projectID: widget.doctorResponse!.projectID,
            language: projectViewModel.isArabic ? "ar" : "en")
        .then((res) {
      GifLoaderDialogUtils.hideDialog(context);
      if (res['MessageStatus'] == 1) {
        AppToast.showSuccessToast(message: res['SuccessMsg']);
        Navigator.of(context).pop();
      } else {
        AppToast.showErrorToast(message: res['ErrorEndUserMessage']);
      }
    }).catchError((err) {
      print(err);
      GifLoaderDialogUtils.hideDialog(context);
    });
  }

  Widget inputWidget(String _labelText, String _hintText, TextEditingController _controller, {String? prefix, bool isEnable = true, bool hasSelection = false}) {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, bottom: 15, top: 15),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: isEnable ? Colors.white : CustomColors.grey2.withOpacity(0.4),
        border: Border.all(
          color: Color(0xffefefef),
          width: 1,
        ),
      ),
      child: InkWell(
        onTap: hasSelection ? () {} : null,
        child: Row(
          children: [
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _labelText,
                    style: TextStyle(
                      fontSize: 11,
                      fontWeight: FontWeight.w600,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                  ),
                  TextField(
                    enabled: isEnable,
                    scrollPadding: EdgeInsets.all(40.0),
                    keyboardType: TextInputType.text,
                    controller: _controller,
                    onChanged: (value) => {},
                    style: TextStyle(
                      fontSize: 14,
                      height: 21 / 14,
                      fontWeight: FontWeight.w400,
                      color: Color(0xff2B353E),
                      letterSpacing: -0.44,
                    ),
                    decoration: InputDecoration(
                      isDense: true,
                      hintText: _hintText,
                      fillColor: CustomColors.accentColor,
                      hintStyle: TextStyle(
                        fontSize: isEnable ? 14 : 24,
                        height: 21 / 14,
                        fontWeight: FontWeight.w400,
                        color: isEnable ? Color(0xff575757) : CustomColors.black,
                        letterSpacing: -0.56,
                      ),
                      prefixIconConstraints: BoxConstraints(minWidth: 50),
                      prefixIcon: prefix == null
                          ? null
                          : Text(
                              "+" + prefix,
                              style: TextStyle(
                                fontSize: 14,
                                height: 21 / 14,
                                fontWeight: FontWeight.w500,
                                color: Color(0xff2E303A),
                                letterSpacing: -0.56,
                              ),
                            ),
                      contentPadding: EdgeInsets.zero,
                      border: InputBorder.none,
                      focusedBorder: InputBorder.none,
                      enabledBorder: InputBorder.none,
                    ),
                  ),
                ],
              ),
            ),
            if (hasSelection) Icon(Icons.keyboard_arrow_down_outlined),
          ],
        ),
      ),
    );
  }
}
