import 'package:barcode_scan/barcode_scan.dart';
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/main/util.dart';
import 'package:fcs/pages/widgets/barcode_scanner.dart';
import 'package:fcs/pages/widgets/bottom_up_page_route.dart';
import 'package:fcs/pages/widgets/input_text.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_icons/flutter_icons.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

const MANAGE_MARKET = "Manage Market";
const SELECT_MARKET = "Select Market";

class TrackingIDPage extends StatefulWidget {
  const TrackingIDPage({Key key}) : super(key: key);
  @override
  _TrackingIDPageState createState() => _TrackingIDPageState();
}

class _TrackingIDPageState extends State<TrackingIDPage> {
  TextEditingController _transcationIDCtl = new TextEditingController();
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    selectedMarket = SELECT_MARKET;
  }

  @override
  Widget build(BuildContext context) {
    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,
          ),
          body: Center(
            child: Padding(
              padding: const EdgeInsets.all(18.0),
              child: ListView(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                          child: InputText(
                        labelTextKey: "package.tracking.id",
                        controller: _transcationIDCtl,
                      )),
                      IconButton(
                        icon: Icon(MaterialCommunityIcons.barcode_scan,
                            size: 30, color: primaryColor),
                        onPressed: _scan,
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 30,
                  ),
                  dropDown(),
                  SizedBox(
                    height: 30,
                  ),
                  fcsButton(context, getLocalString(context, "btn.select"),
                      callack: _select)
                ],
              ),
            ),
          )),
    );
  }

  String selectedMarket;
  Widget dropDown() {
    List<Market> _markets = Provider.of<MarketModel>(context).markets;
    List<String> markets = _markets.map((e) => e.name).toList();
    markets.insert(0, MANAGE_MARKET);
    markets.insert(0, SELECT_MARKET);

    return Row(
      children: [
        Padding(
          padding: const EdgeInsets.only(right: 18.0),
          child: LocalText(
            context,
            "package.create.market",
            color: primaryColor,
            fontSize: 20,
          ),
        ),
        Container(
          width: 150,
          child: DropdownButton<String>(
            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;
                }
                if (newValue == SELECT_MARKET) {
                  selectedMarket = null;
                  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(() {
          _transcationIDCtl.text = barcode;
        });
      }
    } catch (e) {
      print('error: $e');
    }
  }

  _select() {
    if (_transcationIDCtl.text == "" && selectedMarket == null) return;
    Navigator.pop(context,
        Package(trackingID: _transcationIDCtl.text, market: selectedMarket));
  }
}
