
import 'package:flutter/material.dart';

import '../../constants.dart';
import '../../generated/l10n.dart';
import '../../models/key_value.dart';
import '../../routes.dart';
import '../../store/store.dart';
import '../../utils/http_util.dart';
import '../../utils/utils.dart';
import '../../widgets/general/bottom_nav.dart';
import '../../widgets/general/breadcrumbs.dart';
import '../../widgets/general/navigationbar.dart';

class DesktopBuyService extends StatefulWidget {
  final Map<String, dynamic> data;

  const DesktopBuyService(this.data, {Key? key})
      : super(key: key);

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

class DesktopBuyServiceState extends State<DesktopBuyService> {
  double sideSpace = 0;
  double mainSpace = 1200;

  List<KeyValue> plans = [];
  KeyValue selectedPlan;
  double price = 0.0;
  double tax = 0.0;
  double paymentAmount = 0.0;

  @override
  Widget build(BuildContext context) {
    if (MediaQuery.of(context).size.width <= 1200) {
      mainSpace = MediaQuery.of(context).size.width;
      sideSpace = 0;
    } else {
      mainSpace = 1200;
      sideSpace = (MediaQuery.of(context).size.width - 1200) / 2;
    }

    Row row = Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [],
    );

    Column col1 = Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: EdgeInsets.only(bottom: 16),
          child: Text(
            S.of(context).purchase_renew_service,
            style: TextStyle(
              fontSize: 28,
            ),
          ),
        ),
      ],
    );

    col1.children.add(
      Utils.buildLine(S.of(context).service_descritpion, widget.data['service_selections']['description'], valueSize: 16),
    );

    col1.children.add(
      Utils.buildLine(S.of(context).your_group, widget.data['group']['name'], valueSize: 16),
    );

    if (widget.data['store']['id'] != null) {
      col1.children.add(
        Utils.buildLine(S.of(context).store, widget.data['store']['name'], valueSize: 16),
      );
    }

    if (widget.data['domain'] != null) {
      col1.children.add(
        Utils.buildLine(S.of(context).domain_name, widget.data['domain'], valueSize: 16),
      );
    }

    if (widget.data['exists_service'] == null) {
      col1.children.add(
        Utils.buildLine(S.of(context).current_plan, 'N/A', valueSize: 16),
      );
    } else {
      col1.children.add(
        Utils.buildLine(S.of(context).current_plan, widget.data['exists_service']['description'], valueSize: 16),
      );
      col1.children.add(
        Utils.buildLine(S.of(context).expiration_date,
            Utils.utcDatetimeStringToLocalDatetimeString(context,
                widget.data['exists_service']['expiration_date']),
            valueSize: 16
        ),
      );
    }

    col1.children.add(
      Utils.buildLine(S.of(context).select_a_plan, DropdownButton<KeyValue>(
        items: plans.map((e) {
          return DropdownMenuItem<KeyValue>(
            value: e,
            child: Text(e.name),
          );
        }).toList(),
        isExpanded: true,
        hint: Text(
          S.of(context).select_a_plan,
        ),
        onChanged: (newValue) {
          print('newValue $newValue');
          setState(() {
            selectedPlan = newValue;
            price = selectedPlan.value['price'];
            tax = selectedPlan.value['price'] * selectedPlan.value['tax'];
            paymentAmount = price + tax;
          });
        },
        value: selectedPlan,
      ), valueSize: 16),
    );
    col1.children.add(
      Utils.buildLine(S.of(context).price, price.toStringAsFixed(2), valueSize: 16)
    );
    col1.children.add(
        Utils.buildLine(S.of(context).tax, tax.toStringAsFixed(2), valueSize: 16)
    );
    col1.children.add(
        Utils.buildLine(S.of(context).total, paymentAmount.toStringAsFixed(2), valueSize: 32)
    );

    Column col2 = Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: EdgeInsets.only(left: 16, right: 16),
          child: ElevatedButton(
            child: Container(
              padding: EdgeInsets.only(left: 16, right: 16, top: 8, bottom: 8),
              child: Text(
                S.of(context).pay_now,
                style: TextStyle(
                  fontSize: 20,
                ),
              ),
            ),
            onPressed: (paymentAmount > 0) ? () => _submit() : null,
          ),
        ),
      ],
    );

    row.children.add(
        Expanded(
          child: Container(
            padding: EdgeInsets.only(top: 20, left: 16, right: 16, bottom: 20),
            child: col1,
            decoration: BoxDecoration(
              border: Border(
                right: BorderSide(
                  width: 1,
                  color: Colors.black12,
                ),
              ),
            ),
          ),
        )
    );
    row.children.add(
        Expanded(
          child: Container(
            padding: EdgeInsets.only(top: 20, left: 16, right: 16, bottom: 20),
            child: col2,
          ),
        )
    );

    return Scaffold(
      appBar: MiniNavigationBar(
        title: S.of(context).blog,
        back: true,
        breadCrumbs: [
          BreadCrumb(S.of(context).purchase_renew_service, null),
        ],
        breadCrumbHeight: Constants.BREADCRUMB_HEIGHT,
      ),
      body: SingleChildScrollView(
        child: Row(
          children: [
            Container(
              width: sideSpace,
            ),
            Expanded(child: row,),
            Container(
              width: sideSpace,
            ),
          ],
        ),
      ),
      bottomNavigationBar: BottomNav(),
    );
  }

  void _submit() {
    if (store.state.user == null) {
      Utils.requireLogin(context, returnUrl: '/buy-service/${widget.data['group']['id']}/${widget.data['service_selections']['code']}');
      return;
    }
    Map<String, dynamic> newData = widget.data;
    newData['selected_plan'] = selectedPlan.value;
    HttpUtil.httpPost('v1/create-service-buy-renewal-invoice',
          (response) {
        Routes.router.navigateTo(context, '/paynow/${response.data['order_id']}', replace: true);
      },
      body: newData,
    ).onError((error, stackTrace) {
      Utils.showMessageDialog(context, error);
    });
  }

  @override
  void initState() {
    super.initState();
    List o = (widget.data['service_selections']['options'] as List);
    for (int i = 0; i < o.length; i++) {
      Map<String, dynamic> o1 = o[i];
      plans.add(new KeyValue(o1['name'], o1));
    }
  }
}