import 'package:fcs/domain/entities/market.dart';
import 'package:fcs/domain/entities/package.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/market/market_editor.dart';
import 'package:fcs/pages/market/model/market_model.dart';
import 'package:fcs/pages/package/tracking_id_page.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:fcs/pages/widgets/barcode_scanner.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';

class PackageEditor extends StatefulWidget {
  final Package package;
  PackageEditor({this.package});

  @override
  _PackageEditorState createState() => _PackageEditorState();
}

class _PackageEditorState extends State<PackageEditor> {
  TextEditingController _remarkCtl = new TextEditingController();
  TextEditingController _descCtl = new TextEditingController();
  TextEditingController _trackingIDCtl = new TextEditingController();

  bool _isLoading = false;
  bool _isNew;
  MultiImgController multiImgController = MultiImgController();
  Package _package = Package();

  @override
  void initState() {
    super.initState();
    if (widget.package != null) {
      _isNew = false;
      _package = widget.package;
      _trackingIDCtl.text = _package.trackingID;

      selectedMarket = _package.market ?? "";
      _descCtl.text = _package.desc;
      _remarkCtl.text = _package.remark;
      multiImgController.setImageFiles = _package.photoFiles;
    } else {
      _isNew = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    final trackingIDBox = Container(
        child: Row(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: <Widget>[
        Expanded(
            child: InputText(
          iconData: MaterialCommunityIcons.barcode_scan,
          labelTextKey: "processing.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 descBox = InputText(
        labelTextKey: 'processing.desc',
        iconData: MaterialCommunityIcons.message_text_outline,
        controller: _descCtl);

    final remarkBox = InputText(
        labelTextKey: 'processing.remark',
        iconData: Entypo.new_message,
        controller: _remarkCtl);

    final img = MultiImageFile(
      enabled: true,
      controller: multiImgController,
      title: "Receipt File",
    );

    final selectBtn = fcsButton(
      context,
      getLocalString(context, 'processing.package.select.btn'),
      callack: _selectPackage,
    );
    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: widget.package == null
              ? LocalText(
                  context,
                  "processing.package.create",
                  fontSize: 20,
                  color: primaryColor,
                )
              : LocalText(
                  context,
                  "processing.package.update",
                  fontSize: 20,
                  color: primaryColor,
                ),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: ListView(
            children: [
              trackingIDBox,
              SizedBox(
                height: 10,
              ),
              img,
              Divider(),
              SizedBox(
                height: 15,
              ),
              marketDropdown(),
              descBox,
              remarkBox,
              SizedBox(
                height: 20,
              ),
              selectBtn,
              SizedBox(
                height: 20,
              )
            ],
          ),
        ),
      ),
    );
  }

  String selectedMarket;
  Widget marketDropdown() {
    List<Market> _markets = Provider.of<MarketModel>(context).markets;
    List<String> markets = _markets.map((e) => e.name).toList();
    markets.insert(0, MANAGE_MARKET);
    if (!markets.contains(selectedMarket)) {
      markets.insert(0, selectedMarket);
    }

    return Row(
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 0, right: 10),
          child: Icon(Icons.store, color: primaryColor),
        ),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: const EdgeInsets.only(right: 18.0),
                child: LocalText(
                  context,
                  "processing.market",
                  color: Colors.black54,
                  fontSize: 16,
                ),
              ),
              DropdownButton<String>(
                isDense: true,
                value: selectedMarket,
                style: TextStyle(color: Colors.black, fontSize: 14),
                underline: Container(
                  height: 1,
                  color: Colors.grey,
                ),
                onChanged: (String newValue) {
                  setState(() {
                    if (newValue == MANAGE_MARKET) {
                      selectedMarket = null;
                      _manageMarket();
                      return;
                    }
                    selectedMarket = newValue;
                  });
                },
                isExpanded: true,
                items: markets.map<DropdownMenuItem<String>>((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value ?? "",
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            color: value == MANAGE_MARKET
                                ? secondaryColor
                                : primaryColor)),
                  );
                }).toList(),
              ),
            ],
          ),
        ),
      ],
    );
  }

  _manageMarket() {
    Navigator.push<Package>(
      context,
      CupertinoPageRoute(builder: (context) => MarketEditor()),
    );
  }

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

  _selectPackage() async {
    setState(() {
      _isLoading = true;
    });

    try {
      this._package.trackingID = _trackingIDCtl.text;
      this._package.market = selectedMarket;
      this._package.desc = _descCtl.text;
      this._package.remark = _remarkCtl.text;
      this._package.photoFiles = _isNew
          ? multiImgController.getAddedFile
          : multiImgController.getUpdatedFile;

      Navigator.pop<Package>(context, this._package);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
