import 'package:fcs/domain/constants.dart';
import 'package:fcs/domain/entities/faq.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/localization/app_translations.dart';
import 'package:fcs/pages/faq/model/faq_model.dart';
import 'package:fcs/pages/faq/widgets.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:flutter_icons/flutter_icons.dart';
import 'package:provider/provider.dart';

const info = "Select additional page";

class FAQEditor extends StatefulWidget {
  final FAQ faq;
  const FAQEditor({this.faq});
  @override
  _FAQEditorState createState() => _FAQEditorState();
}

class _FAQEditorState extends State<FAQEditor> {
  TextEditingController _sn = new TextEditingController();
  TextEditingController _engQ = new TextEditingController();
  TextEditingController _mmQ = new TextEditingController();
  TextEditingController _engA = new TextEditingController();
  TextEditingController _mmA = new TextEditingController();
  TextEditingController _pageLabelEng = new TextEditingController();
  TextEditingController _pageLabelMm = new TextEditingController();

  final _formKey = GlobalKey<FormState>();
  bool _isLoading = false;
  bool _isNew = false;
  String _pageLink = info;

  @override
  void initState() {
    super.initState();
    _isNew = widget.faq == null;
    if (widget.faq != null) {
      _sn.text = widget.faq.sn.toString();
      _engQ.text = widget.faq.questionEng;
      _mmQ.text = widget.faq.questionMm;
      _engA.text = widget.faq.answerEng;
      _mmA.text = widget.faq.answerMm;
      _pageLabelEng.text = widget.faq.pageLinkLabelEng;
      _pageLabelMm.text = widget.faq.pageLinkLabelMm;
      _pageLink = widget.faq.pageLink;
    }
  }

  @override
  Widget build(BuildContext context) {
    final snBox = InputText(
      controller: _sn,
      labelTextKey: "faq.edit.sn",
      maxLines: 1,
      withBorder: false,
      textInputType: TextInputType.number,
    );

    final questionEngBox = InputText(
      controller: _engQ,
      maxLines: 2,
      withBorder: true,
    );
    final answerEngBox = InputText(
      controller: _engA,
      maxLines: 5,
      withBorder: true,
    );
    final questionMmBox = InputText(
      controller: _mmQ,
      maxLines: 2,
      withBorder: true,
    );
    final answerMmBox = InputText(
      controller: _mmA,
      maxLines: 5,
      withBorder: true,
    );
    final pageLinkBox = DropdownButton<String>(
      value: _pageLink,
      style: TextStyle(color: Colors.deepPurple),
      underline: Container(
        height: 2,
        color: primaryColor,
      ),
      onChanged: (String newValue) {
        setState(() {
          _pageLink = newValue;
        });
      },
      items: <String>[
        info,
        page_buying_instructions,
        page_payment_methods,
        page_rates
      ].map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(
            value,
            style:
                TextStyle(color: value == info ? Colors.black : primaryColor),
          ),
        );
      }).toList(),
    );
    final pageLabelEngBox = InputText(
      controller: _pageLabelEng,
      labelTextKey: "faq.edit.page.label.eng",
    );
    final pageLabelMmBox = InputText(
      controller: _pageLabelMm,
      labelTextKey: "faq.edit.page.label.mm",
    );

    return LocalProgress(
        inAsyncCall: _isLoading,
        child: Scaffold(
            appBar: AppBar(
              centerTitle: true,
              leading: new IconButton(
                icon: new Icon(CupertinoIcons.back, color: primaryColor),
                onPressed: () => Navigator.of(context).pop(),
              ),
              backgroundColor: Colors.white,
              shadowColor: Colors.transparent,
              title: LocalText(
                  context, _isNew ? 'faq.add.title' : 'faq.edit.title',
                  color: primaryColor, fontSize: 20),
              actions: [
                IconButton(
                  icon: Icon(
                    Icons.delete,
                    color: primaryColor,
                  ),
                  onPressed: _delete,
                )
              ],
            ),
            body: Form(
              key: _formKey,
              child: Padding(
                padding: EdgeInsets.only(left: 24.0, right: 24.0),
                child: ListView(
                  children: <Widget>[
                    snBox,
                    Center(child: itemTitle(context, "faq.edit.eng")),
                    subItemTitle(context, "faq.edit.question",
                        iconData: SimpleLineIcons.question),
                    questionEngBox,
                    subItemTitle(context, "faq.edit.answer",
                        iconData: MaterialCommunityIcons.message_reply_text),
                    answerEngBox,
                    Divider(),
                    Center(child: itemTitle(context, "faq.edit.mm")),
                    subItemTitle(context, "faq.edit.question",
                        iconData: SimpleLineIcons.question),
                    questionMmBox,
                    subItemTitle(context, "faq.edit.answer",
                        iconData: MaterialCommunityIcons.message_reply_text),
                    answerMmBox,
                    Divider(),
                    Center(child: itemTitle(context, "faq.edit.page")),
                    pageLinkBox,
                    pageLabelEngBox,
                    pageLabelMmBox,
                    fcsButton(context, getLocalString(context, "btn.save"),
                        callack: _save),
                    SizedBox(
                      height: 20,
                    )
                  ],
                ),
              ),
            )));
  }

  _save() async {
    setState(() {
      _isLoading = true;
    });
    try {
      int sn = int.parse(
        _sn.text,
        onError: (source) => throw Exception("Invalid number"),
      );
      FAQModel faqModel = Provider.of<FAQModel>(context, listen: false);
      FAQ _faq = FAQ(
          sn: sn,
          questionEng: _engQ.text,
          answerEng: _engA.text,
          questionMm: _mmQ.text,
          answerMm: _mmA.text,
          pageLinkLabelEng: _pageLabelEng.text,
          pageLinkLabelMm: _pageLabelMm.text,
          pageLink: _pageLink);
      if (_isNew) {
        await faqModel.addFAQ(_faq);
      } else {
        _faq.id = widget.faq.id;
        await faqModel.updateFAQ(_faq);
      }
      Navigator.pop(context);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  _delete() {
    showConfirmDialog(context, "faq.edit.delete.confirm", _deleteFAQ);
  }

  _deleteFAQ() async {
    setState(() {
      _isLoading = true;
    });
    try {
      FAQModel faqModel = Provider.of<FAQModel>(context, listen: false);
      await faqModel.deleteFAQ(widget.faq);
      Navigator.pop(context);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
