
import 'package:flutter/material.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';

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

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

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

class MobileBuyServiceState extends State<MobileBuyService> {
  List<KeyValue> plans = [];
  late KeyValue selectedPlan;
  double price = 0.0;
  double tax = 0.0;
  double paymentAmount = 0.0;

  @override
  Widget build(BuildContext context) {

    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)
    );
    col1.children.add(
      Container(
        padding: EdgeInsets.only(left: 0, right: 0, top: 16),
        alignment: Alignment.centerRight,
        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,
        ),
      ),
    );

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          onPressed: (){
            Navigator.of(context).pop();
          },
        ),
        title: Text(S.of(context).purchase_renew_service),
        backgroundColor: Theme.of(context).primaryColor,
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.only(top: 20, left: 16, right: 16, bottom: 20),
          child: col1,
        ),
      ),
    );
  }

  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));
    }
  }
}