import 'package:fcs/domain/entities/package.dart';
import 'package:fcs/domain/entities/user.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/package/tracking_id_page.dart';
import 'package:fcs/pages/user_search/user_serach.dart';
import 'package:fcs/pages/staff/model/staff_model.dart';
import 'package:fcs/pages/main/util.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:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'model/package_model.dart';

typedef void FindCallBack();

class PackageNew extends StatefulWidget {
  const PackageNew();
  @override
  _PackageNewState createState() => _PackageNewState();
}

class _PackageNewState extends State<PackageNew> {
  bool _isLoading = false;
  User user;

  List<Package> packages = [];

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

  @override
  Widget build(BuildContext context) {
    var fcsIDBox = Row(
      children: <Widget>[
        Expanded(
            child: DisplayText(
          text: user != null ? user.fcsID : "",
          labelTextKey: "package.create.fcs.id",
          icon: FcsIDIcon(),
        )),
        IconButton(
            icon: Icon(Icons.search, color: primaryColor),
            onPressed: () => searchUser(context, callbackUserSelect: (u) {
                  setState(() {
                    this.user = u;
                  });
                })),
      ],
    );
    final namebox = DisplayText(
      text: user != null ? user.name : "",
      labelTextKey: "package.create.name",
      iconData: Icons.person,
    );
    final phoneNumberBox = DisplayText(
      text: user != null ? user.phoneNumber : "",
      labelTextKey: "package.create.phone",
      iconData: Icons.phone,
    );
    final createButton = fcsButton(
      context,
      getLocalString(context, 'package.create.packages'),
      callack: _create,
    );
    final packageList = Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: new List.generate(
              this.packages.length, (index) => _packageItem(context, index))
          .toList(),
    );

    return LocalProgress(
        inAsyncCall: _isLoading,
        child: Scaffold(
          appBar: AppBar(
            centerTitle: true,
            leading: new IconButton(
              icon: new Icon(CupertinoIcons.back, color: primaryColor, size: 30),
              onPressed: () => Navigator.of(context).pop(),
            ),
            shadowColor: Colors.transparent,
            backgroundColor: Colors.white,
            title: LocalText(
              context,
              "package.create.title",
              fontSize: 20,
              color: primaryColor,
            ),
          ),
          body: Padding(
            padding: const EdgeInsets.only(left: 12.0, right: 12),
            child: ListView(
              children: <Widget>[
                fcsIDBox,
                phoneNumberBox,
                namebox,
                Divider(),
                Center(
                    child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Text("Packages (${packages.length})"),
                    SizedBox(
                      width: 30,
                    ),
                    IconButton(
                      icon: Icon(
                        Icons.add,
                        color: primaryColor,
                      ),
                      onPressed: _addPackage,
                    )
                  ],
                )),
                packageList,
                Divider(),
                SizedBox(
                  height: 20,
                ),
                createButton,
                SizedBox(
                  height: 10,
                ),
              ],
            ),
          ),
        ));
  }

  Widget _packageItem(BuildContext context, int index) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8.0, left: 15),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(packages[index].market ?? ""),
                Text(packages[index].trackingID),
                // DisplayText(
                //   labelText: "Tracking ID",
                //   text: packages[index].trackingID,
                // ),
              ],
            ),
          ),
          IconButton(
            icon: Icon(
              Icons.remove,
              color: primaryColor,
            ),
            onPressed: () {
              setState(() {
                packages.removeAt(index);
              });
            },
          )
        ],
      ),
    );
  }

  _addPackage() async {
    Package package = await Navigator.push<Package>(
      context,
      CupertinoPageRoute(builder: (context) => TrackingIDPage()),
    );

    if (package != null) {
      if (packages.any((e) => e.trackingID == package.trackingID)) {
        showMsgDialog(context, "Error", "Already scanned!");
        return;
      }
      setState(() {
        packages.add(package);
      });
    }
  }

  _create() async {
    if (user == null || packages == null || packages.length == 0) {
      showMsgDialog(context, "Error", "Invalid user!");
      return;
    }
    setState(() {
      _isLoading = true;
    });
    PackageModel packageModel =
        Provider.of<PackageModel>(context, listen: false);
    try {
      await packageModel.createPackages(user, packages);
      Navigator.pop(context);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
