import 'package:fcs/domain/entities/package.dart';
import 'package:fcs/domain/entities/user.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:fcs/pages/package/model/package_model.dart';
import 'package:fcs/pages/user_search/user_serach.dart';
import 'package:fcs/pages/widgets/barcode_scanner.dart';
import 'package:fcs/pages/widgets/display_text.dart';
import 'package:fcs/pages/widgets/fcs_id_icon.dart';
import 'package:fcs/pages/widgets/input_text.dart';
import 'package:fcs/pages/widgets/local_text.dart';
import 'package:fcs/pages/widgets/multi_img_controller.dart';
import 'package:fcs/pages/widgets/multi_img_file.dart';
import 'package:fcs/pages/widgets/progress.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_icons/flutter_icons.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

typedef void FindCallBack();

class ReceivingEditor extends StatefulWidget {
  final Package package;
  const ReceivingEditor({this.package});
  @override
  _ReceivingEditorState createState() => _ReceivingEditorState();
}

class _ReceivingEditorState extends State<ReceivingEditor> {
  Package package = Package();
  bool _isLoading = false;
  bool _isNew;
  User user;
  TextEditingController _trackingIDCtl = new TextEditingController();
  TextEditingController _remarkCtl = new TextEditingController();
  MultiImgController _multiImgController = MultiImgController();

  @override
  void initState() {
    super.initState();
    _isNew = widget.package == null;
    if (!_isNew) {
      package = widget.package;
      _trackingIDCtl.text = package.trackingID;
      _remarkCtl.text = package.remark;
      _multiImgController.setImageUrls = package.photoUrls;
      user = User(
          fcsID: package.fcsID,
          name: package.userName,
          phoneNumber: package.phoneNumber);
    } else {
      package = new Package();
    }
    _trackingIDCtl.addListener(() {
      var text = _trackingIDCtl.text;
      if (text.contains(RegExp(r'[a-z ]'))) {
        text = text.toUpperCase().replaceAll(" ", "");
        _trackingIDCtl.value = _trackingIDCtl.value.copyWith(
          text: text,
          selection:
              TextSelection(baseOffset: text.length, extentOffset: text.length),
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    var fcsIDBox = Row(
      children: <Widget>[
        Expanded(
            child: DisplayText(
          text: user != null ? user.fcsID : "",
          labelTextKey: "receiving.fcs.id",
          icon: FcsIDIcon(),
        )),
        IconButton(
            icon: Icon(Icons.search, color: primaryColor),
            onPressed: () => searchUser(context, callbackUserSelect: (u) {
                  setState(() {
                    this.user = u;
                  });
                })),
      ],
    );

    final trackingIDBox = Container(
        padding: EdgeInsets.only(left: 6),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            Expanded(
                child: InputText(
              iconData: MaterialCommunityIcons.barcode_scan,
              labelTextKey: "receiving.tracking.id",
              controller: _trackingIDCtl,
            )),
            InkWell(
              onTap: _scan,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  children: [
                    Icon(
                      MaterialCommunityIcons.barcode_scan,
                      color: primaryColor,
                    ),
                    Text("Scan")
                  ],
                ),
              ),
            ),
          ],
        ));

    final remarkBox = InputText(
        labelTextKey: 'receiving.remark',
        iconData: Entypo.new_message,
        controller: _remarkCtl);
    final img = MultiImageFile(
      enabled: true,
      controller: _multiImgController,
      title: "Receiving",
    );
    final namebox = DisplayText(
      text: user != null ? user.name : "",
      labelTextKey: "receiving.name",
      iconData: Icons.person,
    );

    final createButton = fcsButton(
      context,
      getLocalString(context, 'receiving.create_btn'),
      callack: _save,
    );

    final updateButton = fcsButton(
      context,
      getLocalString(context, 'receiving.update_btn'),
      callack: _save,
    );

    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,
              _isNew ? "receiving.create" : "receiving.update",
              fontSize: 20,
              color: primaryColor,
            ),
          ),
          body: Padding(
            padding: const EdgeInsets.only(left: 12.0, right: 12),
            child: ListView(
              children: <Widget>[
                trackingIDBox,
                SizedBox(
                  height: 10,
                ),
                remarkBox,
                Divider(),
                img,
                Divider(),
                SizedBox(
                  height: 10,
                ),
                fcsIDBox,
                namebox,
                SizedBox(
                  height: 20,
                ),
                _isNew ? createButton : updateButton,
                SizedBox(
                  height: 10,
                ),
              ],
            ),
          ),
        ));
  }

  _scan() async {
    PermissionStatus permission =
        await PermissionHandler().checkPermissionStatus(PermissionGroup.camera);
    if (permission != PermissionStatus.granted) {
      Map<PermissionGroup, PermissionStatus> permissions =
          await PermissionHandler()
              .requestPermissions([PermissionGroup.camera]);
      if (permissions[PermissionGroup.camera] != PermissionStatus.granted) {
        showMsgDialog(context, "Error", "Camera permission is not granted");
        return null;
      }
    }

    try {
      String barcode = await scanBarcode();
      if (barcode != null) {
        setState(() {
          _trackingIDCtl.text = barcode;
        });
      }
    } catch (e) {
      print('error: $e');
    }
  }

  _save() async {
    package.trackingID = _trackingIDCtl.text;
    package.remark = _remarkCtl.text;

    if (package.trackingID == null || package.trackingID == "") {
      showMsgDialog(context, "Error", "Invalid tracking ID!");
      return;
    }
    setState(() {
      _isLoading = true;
    });
    PackageModel packageModel =
        Provider.of<PackageModel>(context, listen: false);
    try {
      if (_isNew) {
        await packageModel.createReceiving(
            user, package, _multiImgController.getAddedFile);
      } else {
        package.id = widget.package.id;
        await packageModel.updateReceiving(
            user,
            package,
            _multiImgController.getAddedFile,
            _multiImgController.getDeletedUrl);
      }
      Navigator.pop(context);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
