import 'package:diplomaticquarterapp/core/model/AlHabibMedicalService/ComprehensiveMedicalCheckup/GetCMCAllOrdersResponseModel.dart';
import 'package:diplomaticquarterapp/core/viewModels/er/rrt-view-model.dart';
import 'package:diplomaticquarterapp/models/rrt/service_price.dart';
import 'package:diplomaticquarterapp/pages/ErService/rapid-response-team/rrt-order-list-item.dart';
import 'package:diplomaticquarterapp/pages/ErService/rapid-response-team/rrt-pickup-address-page.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/pages/medical/reports/user_agreement_page.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/defaultButton.dart';
import 'package:diplomaticquarterapp/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class RRTRequestPage extends StatefulWidget {
  final List<GetCMCAllOrdersResponseModel> pendingOrders;
  final ServicePrice servicePrice;

  RRTRequestPage({this.pendingOrders, this.servicePrice});

  @override
  State<StatefulWidget> createState() => RRTRequestPageState();
}

class RRTRequestPageState extends State<RRTRequestPage> {
  bool acceptTerms = false;
  RRTViewModel viewModel;

  @override
  Widget build(BuildContext context) {
    return BaseView<RRTViewModel>(
      onModelReady: (vm) {
        viewModel = vm;
      },
      builder: (ctx, vm, widgetState) {
        if (widget.pendingOrders.isNotEmpty)
          return currentOrderContent();
        else
          return requestContent();
      },
    );
  }

  Widget requestContent() {
    return Column(
      children: [
        Expanded(
          child: ListView(
            padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15),
            children: [
              serviceDescription(context),
              SizedBox(height: 20),
              priceTable(context),

              acceptPolicy(),

              Container(height: 0.5, color: Theme.of(context).appBarTheme.color), //  Seperator

              Container(
                  padding: EdgeInsets.only(top: 20, bottom: 5),
                  alignment: Alignment.center,
                  child: Text(TranslationBase.of(context).youCanPayByTheFollowingOptions,
                      style: TextStyle(fontSize: 13, color: Theme.of(context).appBarTheme.color, fontWeight: FontWeight.w500), maxLines: 2)),

              Container(margin: EdgeInsets.only(left: 15.0, right: 15.0, top: 10.0), child: getPaymentMethods())
            ],
          ),
        ),
        actionButtons()
      ],
    );
  }

  Widget currentOrderContent() {
    var orders = widget.pendingOrders;
    return ListView.builder(
        itemCount: orders.length,
        padding: EdgeInsets.all(21),
        itemBuilder: (ctx, idx) {
          var order = orders[idx];
          return RRTLogListItem(order, onCancel: deleteOrder);
        });
  }

  Widget serviceDescription(BuildContext context) => Padding(
        padding: const EdgeInsets.symmetric(horizontal: 10),
        child: Text(
          TranslationBase.of(context).rrtDDetails,
          textAlign: TextAlign.justify,
          style: TextStyle(color: Theme.of(context).appBarTheme.color, fontSize: 15, height: 1.5, fontWeight: FontWeight.w300),
        ),
      );

  Widget priceTable(BuildContext context) {
    var radius = Radius.circular(8);
    String amount = widget.servicePrice.price.toString();
    String vat = widget.servicePrice.vat.toString();
    String total = widget.servicePrice.totalPrice.toString();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Container(
          height: 30,
          decoration: BoxDecoration(color: Theme.of(context).appBarTheme.color, borderRadius: BorderRadius.only(topLeft: radius, topRight: radius)),
          child: Center(child: Text(TranslationBase.of(context).approximateServiceFee, style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w500, letterSpacing: 1))),
        ),
        pricingRow(label: TranslationBase.of(context).patientShare, value: '$amount ${TranslationBase.of(context).sar}'),
        Container(height: 0.5, color: Theme.of(context).appBarTheme.color),
        pricingRow(label: TranslationBase.of(context).patientTaxToDo, value: '$vat ${TranslationBase.of(context).sar}'),
        Container(height: 0.5, color: Theme.of(context).appBarTheme.color),
        pricingRow(label: TranslationBase.of(context).patientShareWithTax, value: '$total ${TranslationBase.of(context).sar}', labelBold: true),
        Container(height: 0.5, color: Theme.of(context).appBarTheme.color),
      ],
    );
  }

  Widget pricingRow({@required String label, @required String value, bool labelBold = false, bool valueBold = false}) {
    return Container(
      height: 40,
      margin: EdgeInsets.symmetric(horizontal: 10),
      child: Row(
        children: [
          Text(label, style: TextStyle(fontSize: 13, color: Theme.of(context).appBarTheme.color, fontWeight: labelBold ? FontWeight.bold : FontWeight.normal)),
          Spacer(),
          Container(
            height: 40,
            color: Theme.of(context).appBarTheme.color,
            width: 0.5,
          ),
          Container(
              alignment: Alignment.center,
              width: MediaQuery.of(context).size.width * 0.25,
              child: Text(value, style: TextStyle(fontSize: 13, color: Theme.of(context).appBarTheme.color, fontWeight: valueBold ? FontWeight.bold : FontWeight.normal))),
        ],
      ),
    );
  }

  Widget acceptPolicy() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10),
      child: Row(
        children: [
          Checkbox(
              value: acceptTerms,
              onChanged: (v) {
                setState(() => acceptTerms = v);
              }),
          SizedBox(width: 10),
          Expanded(child: Text(TranslationBase.of(context).iAcceptTermsConditions, style: TextStyle(fontSize: 13, color: Theme.of(context).appBarTheme.color), maxLines: 2)),
          Container(
            alignment: Alignment.center,
            width: MediaQuery.of(context).size.width * 0.25,
            child: TextButton(
                child: Text(TranslationBase.of(context).clickHere, style: TextStyle(fontSize: 12, color: Colors.blue, fontWeight: FontWeight.w400)),
                onPressed: () {
                  Navigator.push(
                    context,
                    FadePage(
                      page: UserAgreementContent(),
                    ),
                  );
                }),
          )
        ],
      ),
    );
  }

  Widget paymentOptions() => Container(
      height: 30,
      alignment: Alignment.center,
      child: Image.asset(
        "assets/payment_options/payment_options.png",
        fit: BoxFit.fill,
      ));

  Widget actionButtons() {
    return Container(
      margin: EdgeInsets.all(15),
      child: Row(
        children: [
          Expanded(
            child: DefaultButton(
              TranslationBase.of(context).next,
              () {
                if (acceptTerms)
                  goToPickupAddress();
                else
                  AppToast.showErrorToast(message: TranslationBase.of(context).pleaseAcceptTerms);
              },
              color: acceptTerms ? CustomColors.accentColor : Colors.grey,
            ),
          ),
        ],
      ),
    );
  }

  goToPickupAddress() async {
    Navigator.push(
        context,
        FadePage(
            page: RRTRequestPickupAddressPage(
          servicePrice: widget.servicePrice,
        )));
  }

  deleteOrder(GetCMCAllOrdersResponseModel order) async {
    GifLoaderDialogUtils.showMyDialog(context);
    var success = await viewModel.cancelOrderRC(order);
    GifLoaderDialogUtils.hideDialog(context);
    if (success)
      setState(() {
        widget.pendingOrders.remove(order);
      });
    await viewModel.getAllOrdersRC();
  }
}
