import 'package:fcs/domain/entities/role.dart';
import 'package:fcs/domain/vo/delivery_address.dart';
import 'package:fcs/localization/app_translations.dart';
import 'package:fcs/localization/transalation.dart';
import 'package:fcs/pages/delivery_address/delivery_address_list.dart';
import 'package:fcs/pages/delivery_address/model/delivery_address_model.dart';
import 'package:fcs/pages/main/model/language_model.dart';
import 'package:fcs/pages/main/model/main_model.dart';
import 'package:fcs/pages/profile/profile_edit.dart';
import 'package:fcs/pages/widgets/bottom_up_page_route.dart';
import 'package:fcs/pages/widgets/display_text.dart';
import 'package:fcs/pages/widgets/fcs_id_icon.dart';
import 'package:fcs/pages/widgets/local_text.dart';
import 'package:fcs/pages/widgets/progress.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

import '../../helpers/theme.dart';

typedef void ProfileCallback();

class Profile extends StatefulWidget {
  @override
  _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  GlobalKey key = GlobalKey();
  bool _isLoading = false;
  String selectedLanguage;
  TextEditingController bizNameController = new TextEditingController();

  DeliveryAddress _deliveryAddress = new DeliveryAddress();

  static final List<String> languagesList = Translation().supportedLanguages;
  static final List<String> languageCodesList =
      Translation().supportedLanguagesCodes;

  final Map<dynamic, dynamic> languagesMap = {
    languagesList[0]: languageCodesList[0],
    languagesList[1]: languageCodesList[1],
  };

  buildLanguage(LanguageModel languageModel) async {
    var lan = await languageModel.load();
    if (this.selectedLanguage != lan) {
      setState(() {
        this.selectedLanguage = lan;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    var shipmentModel =
        Provider.of<DeliveryAddressModel>(context, listen: false);

    if (shipmentModel.deliveryAddresses.length != 0) {
      _deliveryAddress = shipmentModel.deliveryAddresses[0];
    }
  }

  @override
  Widget build(BuildContext context) {
    MainModel mainModel = Provider.of<MainModel>(context);
    if (mainModel.user == null) {
      return Container();
    }
    final namebox = DisplayText(
      text: mainModel.user.name,
      labelTextKey: "profile.name",
      iconData: Icons.person,
    );

    final phonenumberbox = DisplayText(
      text: mainModel.user.phone,
      labelTextKey: "profile.phone",
      iconData: Icons.phone,
    );
    final fcsIDBox = Row(
      children: [
        Expanded(
          child: DisplayText(
            text: mainModel.user.fcsID,
            labelTextKey: "customer.fcs.id",
            icon: FcsIDIcon(),
          ),
        ),
        IconButton(
          icon: Icon(Icons.content_copy, color: Colors.grey),
          onPressed: () => _copy(
              getLocalString(context, "customer.fcs.id"), mainModel.user.fcsID),
        )
      ],
    );

    final usaShippingAddressBox = Row(
      children: [
        Expanded(
          child: DisplayText(
            text: mainModel.setting.usaAddress,
            labelTextKey: "profile.usa.shipping.address",
            iconData: Icons.location_on,
          ),
        ),
        IconButton(
          icon: Icon(Icons.content_copy, color: Colors.grey),
          onPressed: () => _copy(
              getLocalString(context, "profile.usa.shipping.address"),
              mainModel.setting.usaAddress),
        )
      ],
    );

    final logoutbutton = fcsButton(
        context, getLocalString(context, "profile.logout"),
        callack: _logout, iconData: Icons.exit_to_app);

    return LocalProgress(
      inAsyncCall: _isLoading,
      child: Scaffold(
        key: key,
        appBar: AppBar(
          centerTitle: true,
          leading: IconButton(
            icon: Icon(
              CupertinoIcons.back,
              size: 35,
              color: primaryColor,
            ),
            onPressed: () => Navigator.of(context).pop(),
          ),
          title: LocalText(
            context,
            "profile.title",
            fontSize: 20,
            color: primaryColor,
          ),
          shadowColor: Colors.transparent,
          backgroundColor: Colors.white,
          actions: <Widget>[],
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: <Widget>[
              Expanded(
                child: ListView(
                  shrinkWrap: true,
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Expanded(child: namebox),
                        Padding(
                          padding: const EdgeInsets.only(right: 0),
                          child: IconButton(
                              icon: Icon(Icons.edit, color: Colors.grey),
                              onPressed: _editName),
                        )
                      ],
                    ),
                    mainModel.isCustomer()
                        ? Container()
                        : getPrivilegeBox(context),
                    getShippingAddressList(context),
                    phonenumberbox,
                    fcsIDBox,
                    usaShippingAddressBox,
                    DisplayText(
                      text: mainModel.user.status,
                      labelTextKey: "customer.status",
                      iconData: Icons.add_alarm,
                    ),
                  ],
                ),
              ),
              logoutbutton,
              SizedBox(height: 25)
            ],
          ),
        ),
      ),
    );
  }

  Widget getShippingAddressList(BuildContext context) {
    var languageModel = Provider.of<LanguageModel>(context);
    return ListTileTheme(
      contentPadding: EdgeInsets.all(10),
      child: ExpansionTile(
        title: Text(
          getLocalString(context, 'delivery_addresses'),
          style: languageModel.isEng
              ? TextStyle(
                  fontSize: 16.0,
                  fontWeight: FontWeight.bold,
                  fontStyle: FontStyle.normal,
                )
              : TextStyle(
                  fontSize: 15.0,
                  fontWeight: FontWeight.bold,
                  fontStyle: FontStyle.normal,
                  fontFamily: "Myanmar3"),
        ),
        children: <Widget>[
          showDeliveryAddress(_deliveryAddress),
          Container(
            padding: EdgeInsets.only(top: 20, bottom: 15, right: 15),
            child: Align(
              alignment: Alignment.bottomRight,
              child: Container(
                width: 130,
                height: 40,
                child: FloatingActionButton.extended(
                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  onPressed: () async {
                    DeliveryAddress deliveryAddress = await Navigator.push(
                      context,
                      BottomUpPageRoute(DeliveryAddressList(
                          deliveryAddress: _deliveryAddress)),
                    );
                    setState(() {
                      _deliveryAddress = deliveryAddress;
                    });
                  },
                  label: LocalText(context,
                   'delivery_address.change_address',
                    fontSize: 12,
                    color: Colors.white,
                  ),
                  backgroundColor: primaryColor,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget showDeliveryAddress(DeliveryAddress deliveryAddress) {
    return Container(
      padding: EdgeInsets.only(left: 10, right: 10),
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              Expanded(
                child: new Padding(
                  padding: const EdgeInsets.symmetric(vertical: 10.0),
                  child: Row(
                    children: <Widget>[
                      new Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          Padding(
                            padding: const EdgeInsets.only(left: 8.0),
                            child: new Text(
                              deliveryAddress.fullName == null
                                  ? ''
                                  : deliveryAddress.fullName,
                              style: new TextStyle(
                                  fontSize: 15.0,
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(left: 8.0),
                            child: new Text(
                              deliveryAddress.addressLine1 == null
                                  ? ''
                                  : deliveryAddress.addressLine1,
                              style: new TextStyle(
                                  fontSize: 14.0, color: Colors.grey),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(left: 8.0),
                            child: new Text(
                              deliveryAddress.addressLine2 == null
                                  ? ''
                                  : deliveryAddress.addressLine2,
                              style: new TextStyle(
                                  fontSize: 14.0, color: Colors.grey),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(left: 8.0),
                            child: new Text(
                              deliveryAddress.city == null
                                  ? ''
                                  : deliveryAddress.city,
                              style: new TextStyle(
                                  fontSize: 14.0, color: Colors.grey),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(left: 8.0),
                            child: new Text(
                              deliveryAddress.state == null
                                  ? ''
                                  : deliveryAddress.state,
                              style: new TextStyle(
                                  fontSize: 14.0, color: Colors.grey),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(left: 8.0),
                            child: new Text(
                              deliveryAddress.country == null
                                  ? ''
                                  : deliveryAddress.country,
                              style: new TextStyle(
                                  fontSize: 14.0, color: Colors.grey),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(left: 8.0),
                            child: new Text(
                              deliveryAddress.phoneNumber == null
                                  ? ''
                                  : "Phone:${deliveryAddress.phoneNumber}",
                              style: new TextStyle(
                                  fontSize: 14.0, color: Colors.grey),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  List<Privilege> privileges = [
    Privilege(name: 'Manage shipment'),
    Privilege(name: 'Manage pickups'),
    Privilege(name: 'Manage packages'),
    Privilege(name: 'Manage deliveries'),
    Privilege(name: 'Admin')
  ];

  Widget getPrivilegeBox(BuildContext context) {
    var languageModel = Provider.of<LanguageModel>(context);

    return ListTileTheme(
      contentPadding: EdgeInsets.all(10),
      child: ExpansionTile(
        title: Text(
          AppTranslations.of(context).text("profile.privilege"),
          style: languageModel.isEng
              ? TextStyle(
                  fontSize: 16.0,
                  fontWeight: FontWeight.bold,
                  fontStyle: FontStyle.normal,
                )
              : TextStyle(
                  fontSize: 15.0,
                  fontWeight: FontWeight.bold,
                  fontStyle: FontStyle.normal,
                  fontFamily: "Myanmar3"),
        ),
        children: <Widget>[
          Align(
            alignment: Alignment.topLeft,
            child: SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: getRowPrivilegeWidget(privileges)),
            ),
          )
        ],
      ),
    );
  }

  List<Widget> getRowPrivilegeWidget(List<Privilege> privileges) {
    return privileges.map((p) {
      return Container(
        padding: EdgeInsets.all(8.0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(p.name,
                style: TextStyle(fontSize: 16.0, fontStyle: FontStyle.normal)),
            SizedBox(
              width: 30,
            ),
            Container(
              child: Text(
                "- ${p.desc}",
                style: TextStyle(fontSize: 16.0, fontStyle: FontStyle.normal),
              ),
            )
          ],
        ),
      );
    }).toList();
  }

  _copy(String title, String data) {
    Clipboard.setData(ClipboardData(text: data));
    _showToast(title);
  }

  void _showToast(String title) {
    final ScaffoldState scaffold = key.currentState;
    scaffold.showSnackBar(
      SnackBar(
        content: Text('copied "$title" data to clipboard'),
        backgroundColor: secondaryColor,
        duration: Duration(seconds: 1),
      ),
    );
  }

  _editName() {
    Navigator.of(context)
        .push<void>(CupertinoPageRoute(builder: (context) => ProfileEdit()));
  }

  _logout() {
    showConfirmDialog(context, "profile.logout.confirm", () async {
      setState(() {
        _isLoading = true;
      });
      try {
        await context.read<MainModel>().signout();
        Navigator.of(context).pushNamedAndRemoveUntil(
            "/welcome", ModalRoute.withName('/welcome'));
      } catch (e) {} finally {
        Future.delayed(Duration(seconds: 1), () {
          if (mounted) {
            setState(() {
              _isLoading = false;
            });
          }
        });
      }
    });
  }
}
