import 'package:diplomaticquarterapp/core/service/AuthenticatedUserObject.dart';
import 'package:diplomaticquarterapp/core/viewModels/TermsConditionsViewModel.dart';
import 'package:diplomaticquarterapp/core/viewModels/appointment_rate_view_model.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/models/Appointments/toDoCountProviderModel.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/pages/landing/landing_page.dart';
import 'package:diplomaticquarterapp/pages/rateAppointment/rate_appointment_doctor.dart';
import 'package:diplomaticquarterapp/services/authentication/auth_provider.dart';
import 'package:diplomaticquarterapp/services/clinic_services/get_clinic_service.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/custom_text_button.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:provider/provider.dart';
import 'package:webview_flutter/webview_flutter.dart';

class UserLoginAgreementPage extends StatefulWidget {
  final String userAgreementText;
  final AuthenticatedUserObject authenticatedUserObject;
  final AppointmentRateViewModel appointmentRateViewModel;
  final int selectedOption;

  UserLoginAgreementPage({required this.userAgreementText, required this.authenticatedUserObject, required this.appointmentRateViewModel, required this.selectedOption});

  @override
  State<UserLoginAgreementPage> createState() => _UserLoginAgreementPageState();
}

class _UserLoginAgreementPageState extends State<UserLoginAgreementPage> {
  late ProjectViewModel projectViewModel;
  late ToDoCountProviderModel toDoProvider;
  final authService = AuthProvider();

  late final WebViewController _controller;
  bool isPageLoaded = false;

  @override
  void initState() {
    super.initState();
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            // Update loading bar.
          },
          onPageStarted: (String url) {},
          onPageFinished: (String url) {
            setState(() {
              isPageLoaded = true;
            });
          },
          onHttpError: (HttpResponseError error) {},
          onWebResourceError: (WebResourceError error) {},
          onNavigationRequest: (NavigationRequest request) {
            if (request.url.startsWith('https://www.youtube.com/')) {
              return NavigationDecision.prevent;
            }
            return NavigationDecision.navigate;
          },
        ),
      )
      ..loadRequest(Uri.parse("https://hmg.com/en/Pages/Privacy.aspx"));
  }

  @override
  Widget build(BuildContext context) {
    projectViewModel = Provider.of(context);
    toDoProvider = Provider.of<ToDoCountProviderModel>(context);
    return BaseView<TermsConditionsViewModel>(
      builder: (_, model, w) => AppScaffold(
        isShowAppBar: true,
        showNewAppBarTitle: true,
        showNewAppBar: true,
        isShowDecPage: false,
        appBarTitle: TranslationBase.of(context).userAgreement,
        body: WebViewWidget(controller: _controller),
        // Padding(
        //   padding: const EdgeInsets.all(8.0),
        //   child: SingleChildScrollView(child: WebViewWidget(controller: _controller)
        //       // Html(
        //       //   data: widget.userAgreementText,
        //       // ),
        //       ),
        // ),
        bottomSheet: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(topLeft: Radius.circular(10), topRight: Radius.circular(10), bottomLeft: Radius.circular(10), bottomRight: Radius.circular(10)),
            boxShadow: [
              BoxShadow(
                color: Colors.grey.withOpacity(0.5),
                spreadRadius: 5,
                blurRadius: 7,
                offset: Offset(0, 3), // changes position of shadow
              ),
            ],
          ),
          padding: EdgeInsets.only(left: 21, right: 21, top: 15, bottom: 15),
          width: double.infinity,
          // color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(height: 12),
              Text(
                TranslationBase.of(context).continueAgreeTerms,
                style: TextStyle(
                  fontSize: 16.0,
                  fontWeight: FontWeight.w600,
                  color: Color(0xff2B353E),
                  letterSpacing: -0.64,
                ),
              ),
              SizedBox(height: 12),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: ButtonTheme(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10.0),
                      ),
                      height: 45.0,
                      child: CustomTextButton(
                        backgroundColor: CustomColors.green,
                        elevation: 0,
                        onPressed: isPageLoaded
                            ? () {
                                addUsageAgreement();
                              }
                            : null,
                        child: Text(TranslationBase.of(context).acceptLbl.toUpperCase(),
                            style: TextStyle(
                              fontSize: 18.0,
                              color: Colors.white,
                            )),
                      ),
                    ),
                  ),
                  mWidth(7),
                  Expanded(
                    flex: 1,
                    child: ButtonTheme(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(10.0),
                      ),
                      height: 45.0,
                      child: CustomTextButton(
                        backgroundColor: Color(0xffc5272d),
                        elevation: 0,
                        onPressed: isPageLoaded
                            ? () {
                                Navigator.pushAndRemoveUntil(
                                    context,
                                    FadePage(
                                      page: LandingPage(),
                                    ),
                                    (r) => false);
                              }
                            : null,
                        child: Text(TranslationBase.of(context).declineLbl.toUpperCase(), style: TextStyle(fontSize: 18.0, color: Colors.white)),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  addUsageAgreement() {
    GifLoaderDialogUtils.showMyDialog(context);
    this.authService.addUserAgreementContent().then((result) {
      goToHome();
    }).catchError((err) {
      GifLoaderDialogUtils.hideDialog(context);
      AppToast.showErrorToast(message: err);
      print(err);
    });
  }

  goToHome() async {
    widget.authenticatedUserObject.isLogin = true;
    widget.appointmentRateViewModel.isLogin = true;
    projectViewModel.isLogin = true;
    projectViewModel.user = widget.authenticatedUserObject.user;
    await widget.authenticatedUserObject.getUser(getUser: true);

    // GifLoaderDialogUtils.hideDialog(context);
    getToDoCount();
    widget.appointmentRateViewModel
        .getIsLastAppointmentRatedList(projectViewModel.isArabic ? 1 : 2)
        .then((value) => {
              GifLoaderDialogUtils.hideDialog(context),
              if (widget.appointmentRateViewModel.isHaveAppointmentNotRate)
                {
                  Navigator.pushAndRemoveUntil(
                      context,
                      FadePage(
                        page: RateAppointmentDoctor(),
                      ),
                      (r) => false)
                }
              else
                {
                  GifLoaderDialogUtils.hideDialog(context),
                  Navigator.pushAndRemoveUntil(
                      context,
                      FadePage(
                        page: LandingPage(),
                      ),
                      (r) => false)
                },
              insertIMEI()
            })
        .catchError((err) {
      print(err);
    });
  }

  insertIMEI() {
    authService.insertDeviceImei(widget.selectedOption).then((value) => {}).catchError((err) {
      print(err);
    });
  }

  getToDoCount() {
    toDoProvider.setState(0, 0, true, "0");
    ClinicListService service = new ClinicListService();
    service.getActiveAppointmentNo(context).then((res) {
      if (res['MessageStatus'] == 1) {
        toDoProvider.setState(res['AppointmentActiveNumber'], res['AncillaryOrderListCount'], true, "0");
        // toDoProvider.setState(res['AppointmentActiveNumber'], true, "0");
      } else {}
    }).catchError((err) {
      print(err);
    });
  }
}
