import 'package:fcs/domain/entities/user.dart';
import 'package:fcs/domain/vo/delivery_address.dart';
import 'package:fcs/domain/vo/privilege.dart';
import 'package:fcs/localization/transalation.dart';
import 'package:fcs/pages/delivery_address/delivery_address_list.dart';
import 'package:fcs/pages/delivery_address/delivery_address_row.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/main/util.dart';
import 'package:fcs/pages/profile/profile_currency_edit.dart';
import 'package:fcs/pages/profile/profile_edit.dart';
import 'package:fcs/pages/staff/model/staff_model.dart';
import 'package:fcs/pages/widgets/bottom_up_page_route.dart';
import 'package:fcs/pages/widgets/defalut_delivery_address.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:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_icons/flutter_icons.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();

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

  @override
  Widget build(BuildContext context) {
    MainModel mainModel = Provider.of<MainModel>(context);
    if (mainModel.user == null) {
      return Container();
    }
    DeliveryAddressModel deliveryAddressModel =
        Provider.of<DeliveryAddressModel>(context);

    final namebox = DisplayText(
      text: mainModel.user.name + " (${mainModel.user.status})",
      labelTextKey: "profile.name",
      iconData: Icons.person,
    );
    final currencyBox = DisplayText(
      text: mainModel.user.preferCurrency,
      labelTextKey: "profile.currency",
      iconData: FontAwesome5.money_bill_alt,
    );

    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,
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: ListView(
            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),
                  )
                ],
              ),
              phonenumberbox,
              fcsIDBox,
              usaShippingAddressBox,
              Row(
                children: <Widget>[
                  Expanded(child: currencyBox),
                  Padding(
                    padding: const EdgeInsets.only(right: 0),
                    child: IconButton(
                        icon: Icon(Icons.edit, color: Colors.grey),
                        onPressed: _editCurrency),
                  )
                ],
              ),
              DefaultDeliveryAddress(
                labelKey: "profile.default.delivery.address",
                deliveryAddress: deliveryAddressModel.defalutAddress,
                onTap: () {
                  Navigator.push(
                      context,
                      CupertinoPageRoute(
                          builder: (context) => DeliveryAddressList()));
                },
              ),
              getPrivilegeBox(context),
              SizedBox(height: 15),
              logoutbutton,
              SizedBox(height: 25)
            ],
          ),
        ),
      ),
    );
  }

  Widget getPrivilegeBox(BuildContext context) {
    User user = Provider.of<MainModel>(context, listen: false).user;
    List<Privilege> _privileges =
        Provider.of<StaffModel>(context, listen: false).privileges;

    if (user == null || user.isCustomer()) return Container();
    List<Privilege> privileges = [];
    user.privileges.forEach((e) {
      var p = _privileges.firstWhere((p) => p.id == e, orElse: () => null);
      if (p != null) {
        privileges.add(p);
      }
    });

    return Column(
      children: <Widget>[
        DisplayText(
          labelTextKey: "profile.privileges",
          iconData: MaterialCommunityIcons.clipboard_check_outline,
        ),
        Padding(
          padding: const EdgeInsets.only(left: 30.0),
          child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: getRowPrivilegeWidget(privileges)),
        )
      ],
    );
  }

  List<Widget> getRowPrivilegeWidget(List<Privilege> privileges) {
    return privileges.map((p) {
      return Container(
        padding: EdgeInsets.all(3.0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Icon(
              p.iconData,
              color: Colors.black38,
            ),
            SizedBox(
              width: 10,
            ),
            Flexible(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("${p.name}",
                      style: TextStyle(
                        fontSize: 16.0,
                        fontStyle: FontStyle.normal,
                        color: primaryColor,
                      )),
                  Text(
                    "${p.desc}",
                    style: TextStyle(
                        fontSize: 14.0,
                        fontStyle: FontStyle.normal,
                        color: Colors.black38),
                  ),
                ],
              ),
            )
          ],
        ),
      );
    }).toList();
  }

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

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

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

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