

import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

import '../../constants.dart';
import '../../events/eventbus.dart';
import '../../events/events.dart';
import '../../generated/l10n.dart';
import '../../models/address.dart';
import '../../pages/edit_address.dart';
import '../../routes.dart';
import '../../store/actions.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 DesktopMyAddresses extends StatefulWidget {
  final int businessId;
  const DesktopMyAddresses({Key? key, this.businessId}) : super(key: key);

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

}

class DesktopMyAddressesState extends State<DesktopMyAddresses> {
  List<Address> addresses;

  double sideSpace = 0;
  double mainSpace = 1200;

  double division = 2;

  @override
  Widget build(BuildContext context) {
    store.dispatch(UpdateContext(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;
    }

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

    BuildContext mainContext = context;

    return Scaffold(
      appBar: MiniNavigationBar(
        title: S.of(context).my_addresses,
        back: true,
        breadCrumbs: [
          BreadCrumb(S.of(context).my_addresses, null),
          BreadCrumb(S.of(context).add_new_address,
            '/search-place/${widget.businessId}',
          ),
        ],
        breadCrumbHeight: Constants.BREADCRUMB_HEIGHT,
      ),
      body: SingleChildScrollView(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              width: sideSpace,
            ),
            Container(
              width: mainSpace,
              padding: EdgeInsets.only(
                top: 12.0,
                bottom: 16.0,
                left: 8.0,
                right: 8.0,
              ),
              child: addresses == null ? Text('') :
              (addresses.length > 0 ?
              Wrap(
                children: addresses.map((a) => _getAddress(a)).toList(),
              ) :
              Center(
                child: Text(S.of(context).no_address_yet),
              )),
            ),
            Container(
              width: sideSpace,
            ),
          ],
        ),
      ),
      bottomNavigationBar: BottomNav(),
    );
  }
  
  Widget _getAddress(Address address) {

    return Container(
      width: (mainSpace - 16.0) / division,
      padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 8.0),
      child: Container(
        padding: EdgeInsets.only(top: 20.0, bottom: 20.0, left: 16.0, right: 16.0,),
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(
              color: Colors.black12,
              width: 0.6,
            ),
            top: BorderSide(
              color: Colors.black12,
              width: 0.6,
            ),
            left: BorderSide(
              color: Colors.black12,
              width: 0.6,
            ),
            right: BorderSide(
              color: Colors.black12,
              width: 0.6,
            ),
          ),
          borderRadius: BorderRadius.all(Radius.circular(10.0)),
        ),
        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,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  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(context, error, onOk: () {
                            Navigator.of(context).pop();
                            Navigator.of(context).pop();
                          });
                        });
                      },
                    ) : SizedBox.shrink(),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

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

}