import 'package:fcs/domain/entities/market.dart';
import 'package:fcs/domain/entities/package.dart';
import 'package:fcs/domain/entities/user.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/model/package_model.dart';
import 'package:fcs/pages/package/tracking_id_page.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:fcs/pages/user_search/user_serach.dart';
import 'package:fcs/pages/widgets/bottom_up_page_route.dart';
import 'package:fcs/pages/widgets/display_text.dart';
import 'package:fcs/pages/widgets/fcs_id_icon.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:intl/intl.dart';
import 'package:provider/provider.dart';

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

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

class _ProcessingEditorState extends State<ProcessingEditor> {
  TextEditingController _remarkCtl = new TextEditingController();
  TextEditingController _descCtl = new TextEditingController();

  Package _package;
  User _user;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _package = widget.package;
    selectedMarket = _package.market ?? "";
    _descCtl.text = _package.desc;
    _remarkCtl.text = _package.remark;
    multiImgController.setImageUrls = _package.photoUrls;
    _user = User(
        fcsID: _package.fcsID ?? "",
        name: _package.userName ?? "",
        phoneNumber: _package.phoneNumber ?? "");
  }

  final DateFormat dateFormat = DateFormat("d MMM yyyy");

  bool isNew = false;
  MultiImgController multiImgController = MultiImgController();

  @override
  Widget build(BuildContext context) {
    var fcsIDBox = Row(
      children: <Widget>[
        Expanded(
            child: DisplayText(
          text: _user.fcsID,
          labelTextKey: "processing.fcs.id",
          icon: FcsIDIcon(),
        )),
        IconButton(
            icon: Icon(Icons.search, color: primaryColor),
            onPressed: () => searchUser(context, callbackUserSelect: (u) {
                  setState(() {
                    this._user = u;
                  });
                })),
      ],
    );
    final namebox = DisplayText(
      text: _user.name,
      labelTextKey: "processing.name",
      iconData: Icons.person,
    );
    final phoneNumberBox = DisplayText(
      text: _user.phoneNumber,
      labelTextKey: "processing.phone",
      iconData: Icons.phone,
    );

    final trackingIdBox = DisplayText(
      text: _package.trackingID,
      labelTextKey: "processing.tracking.id",
      iconData: MaterialCommunityIcons.barcode_scan,
    );
    final completeProcessingBtn = fcsButton(
      context,
      getLocalString(context, 'processing.edit.complete.btn'),
      callack: _completeProcessing,
    );
    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",
    );
    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,
            "processing.edit.title",
            fontSize: 20,
            color: primaryColor,
          ),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: ListView(
            children: [
              trackingIdBox,
              fcsIDBox,
              namebox,
              phoneNumberBox,
              marketDropdown(),
              descBox,
              remarkBox,
              img,
              completeProcessingBtn,
              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 Padding(
      padding: const EdgeInsets.only(left: 5.0, right: 0),
      child: 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()),
    );
  }

  _completeProcessing() async {
    if (_descCtl.text == "") {
      showMsgDialog(context, "Error", "Expected some description");
      return;
    }
    if (_user.fcsID == null || _user.fcsID == "") {
      showMsgDialog(context, "Error", "Expected FCS-ID");
      return;
    }
    setState(() {
      _isLoading = true;
    });
    PackageModel packageModel =
        Provider.of<PackageModel>(context, listen: false);
    try {
      _package.fcsID = _user.fcsID;
      _package.desc = _descCtl.text;
      _package.remark = _remarkCtl.text;
      _package.market = selectedMarket;
      await packageModel.updateProcessing(_package,
          multiImgController.getAddedFile, multiImgController.getDeletedUrl);
      Navigator.pop(context);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
