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

typedef void FindCallBack();

class MarketEditor extends StatefulWidget {
  const MarketEditor();
  @override
  _MarketEditorState createState() => _MarketEditorState();
}

class _MarketEditorState extends State<MarketEditor> {
  TextEditingController _marketNameCtl = new TextEditingController();

  bool _isLoading = false;
  List<String> markets = [];

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

  List<Widget> showMarkets(BuildContext context, List<Market> markets) {
    return markets.map((p) {
      return new ListTile(
          title: new Row(
        children: <Widget>[
          Expanded(
            child: new Text(
              p.name,
              style: TextStyle(
                fontSize: 15.0,
              ),
            ),
          ),
          Spacer(),
          IconButton(
            icon: Icon(Icons.remove, color: primaryColor),
            onPressed: () => _remove(p),
          )
        ],
      ));
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    List<Market> markets = Provider.of<MarketModel>(context).markets;

    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,
              "market.edit.title",
              fontSize: 20,
              color: primaryColor,
            ),
          ),
          body: Padding(
            padding: const EdgeInsets.only(left: 12.0, right: 12),
            child: ListView(
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(right: 18.0),
                      child: IconButton(
                        icon: Icon(Icons.add, color: primaryColor),
                        onPressed: () => _showDialog(context),
                      ),
                    ),
                  ],
                ),
                Column(
                  children: showMarkets(context, markets),
                ),
                SizedBox(
                  height: 10,
                )
              ],
            ),
          ),
        ));
  }

  _remove(Market market) {
    if (market == null) {
      showMsgDialog(context, "Esrror", "Invalid market!");
      return;
    }
    showConfirmDialog(
        context, "market.remove.confirm", () => _removeMarket(market));
  }

  _removeMarket(Market market) async {
    setState(() {
      _isLoading = true;
    });
    MarketModel marketModel = Provider.of<MarketModel>(context, listen: false);
    try {
      await marketModel.deleteMarket(market.id);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  _add() async {
    if (_marketNameCtl.text == "") {
      showMsgDialog(context, "Esrror", "Invalid market name!");
      return;
    }
    setState(() {
      _isLoading = true;
    });
    MarketModel marketModel = Provider.of<MarketModel>(context, listen: false);
    try {
      await marketModel.addMarket(_marketNameCtl.text);
      _marketNameCtl.text = "";
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  _showDialog(BuildContext context) async {
    await showDialog<String>(
      context: context,
      child: new AlertDialog(
        contentPadding: const EdgeInsets.all(16.0),
        content: new Row(
          children: <Widget>[
            new Expanded(
              child: InputText(
                labelTextKey: "market.edit.name",
                controller: _marketNameCtl,
                autoFocus: true,
              ),
            )
          ],
        ),
        actions: <Widget>[
          new FlatButton(
              child: LocalText(context, "btn.cancel", color: primaryColor),
              onPressed: () {
                Navigator.pop(context);
              }),
          new FlatButton(
              child: LocalText(
                context,
                "btn.save",
                color: primaryColor,
              ),
              onPressed: () {
                Navigator.pop(context);
                _add();
              })
        ],
      ),
    );
  }
}
