

import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_wisetronic/events/eventbus.dart';
import 'package:flutter_wisetronic/events/events.dart';
import 'package:flutter_wisetronic/generated/l10n.dart';
import 'package:flutter_wisetronic/models/address.dart';
import 'package:flutter_wisetronic/pages/edit_address.dart';
import 'package:flutter_wisetronic/store/actions.dart';
import 'package:flutter_wisetronic/store/store.dart';
import 'package:flutter_wisetronic/utils/http_util.dart';
import 'package:flutter_wisetronic/utils/utils.dart';
import 'package:flutter_wisetronic/widgets/mobile/MobileBottomNav.dart';

import '../../routes.dart';

class MobileMyAddresses extends StatefulWidget {
  final int businessId;
  const MobileMyAddresses({Key? key, this.businessId}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return MobileMyAddressesState();
  }

}

class MobileMyAddressesState extends State<MobileMyAddresses> {
  List<Address> addresses;

  @override
  Widget build(BuildContext context) {
    store.dispatch(UpdateContext(context));

    if (addresses == null) {
      return new Scaffold(
        body: Center(
          child: SpinKitWave(
            color: Colors.lightBlueAccent,
            size: 40.0,
          ),
        ),
      );
    }

    BuildContext mainContext = context;

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        title: Text(S.of(context).my_addresses),
        backgroundColor: Theme.of(context).primaryColor,
        actions: [
          IconButton(
            padding: EdgeInsets.only(right: 16.0),
            icon: Icon(
              Icons.add,
              size: 32.0,
            ),
            onPressed: () {
              Routes.router.navigateTo(context, '/search-place/${widget.businessId}');
            }
          ),
        ],
      ),
      body: ListView.builder(
          itemCount: addresses.length <= 1 ? 1 : addresses.length,
          itemBuilder: (BuildContext context, int i) {
            if (addresses.length <= 0) {
              return Container(
                padding: EdgeInsets.all(16.0),
                child: Center(
                  child: Text(S.of(context).no_address_yet),
                ),
              );
            } else {
              Address address = addresses[i];

              return Container(
                padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 16.0),
                decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(
                          color: Colors.black12,
                          width: 0.6,
                        )
                    )
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Expanded(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            child: Text(
                              address.addressLine1,
                              style: TextStyle(
                                fontSize: 19.0,
                              ),
                            ),
                          ),
                          Container(
                            child: Text(
                              address.addressLine2,
                              style: TextStyle(
                                fontSize: 13.0,
                                color: Colors.grey,
                              ),
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: 10.0),
                            child: Text(
                              '${address.contactName} ${Utils.safePhoneNumber(address.phone)}',
                              style: TextStyle(
                                fontSize: 15.0,
                                color: Colors.black87,
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                    Container(
                      child: widget.businessId == 0 ?
                      IconButton(
                        icon: Icon(
                          Icons.edit,
                          color: Colors.grey,
                        ),
                        onPressed: () {
                          Navigator.push(context, MaterialPageRoute(
                            builder: (BuildContext context) => new EditAddress(address, businessId: 0,),
                          ));
                        },
                      ) :
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: <Widget>[
                          Container(
                            margin: EdgeInsets.only(right: 5.0),
                            child: IconButton(
                              icon: Icon(
                                Icons.edit,
                                color: Colors.grey,
                              ),
                              onPressed: () {
                                Navigator.push(context, MaterialPageRoute(
                                  builder: (BuildContext context) => new EditAddress(address, businessId: widget.businessId,),
                                ));
                              },
                            ),
                          ),
                          Container(
                            child: widget.businessId > 0 ? IconButton(
                              icon: Icon(
                                Icons.check,
                                color: Colors.grey,
                              ),
                              onPressed: () {
                                HttpUtil.httpPut('v1/select-address/${address.id}', (response) {
                                  Routes.router.navigateTo(context, '/checkout/${widget.businessId}', replace: true);
                                }).catchError((error) {
                                  Utils.showMessageDialog(mainContext, error, onOk: () {
                                    Navigator.of(mainContext).pop();
                                    Navigator.of(mainContext).pop();
                                  });
                                });
                              },
                            ) : SizedBox.shrink(),
                          )
                        ],
                      ),
                    ),
                  ],
                ),
              );
            }
          }
      ),
      bottomNavigationBar: MobileBottomNav(currentIndex: 3,),
    );
  }

  @override
  void initState() {
    super.initState();
    loadAddresses();

    eventBus.on<OnAddressesUpdated>().listen((event) {
      if (mounted) {
        setState(() {
          addresses = null;
        });
      }
      loadAddresses();
    });
  }

  void loadAddresses() {
    HttpUtil.httpGet(
      'v1/addresses',
    ).then((value) {
      if (mounted) {
        setState(() {
          addresses = (value as List).map((e) => Address.fromJson(e)).toList();
        });
      }
    }).catchError((error) {
      Utils.showMessageDialog(context, error, onOk: () {
        Navigator.of(context).pop();
        Navigator.of(context).pop();
      });
    });
  }

}