import 'package:barcode_scan/barcode_scan.dart';
import 'package:fcs/domain/entities/package.dart';
import 'package:fcs/domain/entities/user.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/user_search/user_serach.dart';
import 'package:fcs/pages/main/util.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/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 ReceivingNew extends StatefulWidget {
  const ReceivingNew();
  @override
  _ReceivingNewState createState() => _ReceivingNewState();
}

class _ReceivingNewState extends State<ReceivingNew> {
  bool _isLoading = false;
  User user;
  TextEditingController _transcationIDCtl = new TextEditingController();
  TextEditingController _remarkCtl = new TextEditingController();
  MultiImgController multiImgController = MultiImgController();

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

  @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(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Expanded(
                child: InputText(
              labelTextKey: "receiving.tracking.id",
              controller: _transcationIDCtl,
            )),
            IconButton(
              icon: Icon(MaterialCommunityIcons.barcode_scan,
                  color: primaryColor),
              onPressed: _scan,
            ),
          ],
        ));

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

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

    return LocalProgress(
        inAsyncCall: _isLoading,
        child: Scaffold(
          appBar: AppBar(
            centerTitle: true,
            leading: new IconButton(
              icon: new Icon(Icons.close, color: primaryColor, size: 30),
              onPressed: () => Navigator.of(context).pop(),
            ),
            shadowColor: Colors.transparent,
            backgroundColor: Colors.white,
            title: LocalText(
              context,
              "receiving.new",
              fontSize: 20,
              color: primaryColor,
            ),
          ),
          body: Padding(
            padding: const EdgeInsets.only(left: 12.0, right: 12),
            child: ListView(
              children: <Widget>[
                trackingIDBox,
                SizedBox(
                  height: 10,
                ),
                img,
                remarkBox,
                SizedBox(
                  height: 10,
                ),
                fcsIDBox,
                phoneNumberBox,
                namebox,
                SizedBox(
                  height: 20,
                ),
                createButton,
                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 BarcodeScanner.scan();
      if (barcode != null) {
        setState(() {
          _transcationIDCtl.text = barcode;
        });
      }
    } catch (e) {
      print('error: $e');
    }
  }

  _create() async {
    if (user == null) {
      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;
      });
    }
  }
}
