import 'dart:convert';

import 'package:fcs/domain/entities/setting.dart';
import 'package:fcs/domain/vo/term.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/main/model/language_model.dart';
import 'package:fcs/pages/main/model/main_model.dart';
import 'package:fcs/pages/term/term_edit.dart';
import 'package:fcs/pages/widgets/local_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:zefyrka/zefyrka.dart';

typedef void ProfileCallback();

class TermPage extends StatefulWidget {
  const TermPage({
    Key? key,
  }) : super(key: key);
  @override
  _TermPageState createState() => _TermPageState();
}

class _TermPageState extends State<TermPage> {
  late ZefyrController _controller;
  late FocusNode _focusNode;
  late NotusDocument document = new NotusDocument();
  bool isLoading = false;

  @override
  void initState() {
    super.initState();
    _focusNode = FocusNode();
  }

  NotusDocument _loadDocument(Setting? setting) {
    bool isEng = Provider.of<LanguageModel>(context).isEng;
    String? term = isEng ? (setting!.termsEng ?? "") : (setting!.termsMm ?? "");
    late NotusDocument doc;
    try {
      doc = NotusDocument.fromJson(jsonDecode(term));
    } catch (e) {}
    if (doc == null) {
      doc = NotusDocument();
    }
    return doc;
  }

  @override
  Widget build(BuildContext context) {
    Setting? setting = Provider.of<MainModel>(context).setting;
    bool isEditable = context.select((MainModel m) => m.termEditable());

    return Scaffold(
      appBar: AppBar(
        shadowColor: Colors.transparent,
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: new IconButton(
          icon: new Icon(
            CupertinoIcons.back,
            color: primaryColor,
          ),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: LocalText(
          context,
          'term',
          color: primaryColor,
          fontSize: 20,
        ),
        actions: isEditable
            ? [
                IconButton(
                    onPressed: () =>
                        Navigator.of(context).push<void>(CupertinoPageRoute(
                          builder: (context) =>
                              TermEdit(term: Term.fromSetting(setting!)),
                        )),
                    icon: Icon(
                      Icons.edit,
                      color: primaryColor,
                    ))
              ]
            : [],
      ),
      body: ZefyrEditor(
        padding: EdgeInsets.all(16),
        controller: ZefyrController(_loadDocument(setting)),
        focusNode: _focusNode,
      ),
    );
  }
}
