import 'package:fcs/domain/entities/market.dart';
import 'package:fcs/domain/entities/package.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/main/util.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/widgets/display_text.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 PackageEditorPage extends StatefulWidget {
  final Package package;
  PackageEditorPage({this.package});

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

class _PackageEditorPageState extends State<PackageEditorPage> {
  TextEditingController _remarkCtl = new TextEditingController();
  TextEditingController _descCtl = new TextEditingController();

  Package _package;
  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;
  }

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

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

  @override
  Widget build(BuildContext context) {
    final trackingIdBox = DisplayText(
      text: _package.trackingID,
      labelTextKey: "package.tracking.id",
      iconData: MaterialCommunityIcons.barcode_scan,
    );
    final statusBox = DisplayText(
      text: _package.status,
      labelTextKey: "package.edit.status",
      iconData: AntDesign.exclamationcircleo,
    );
    final customerNameBox = DisplayText(
      text: _package.userName,
      labelTextKey: "package.create.name",
      iconData: Icons.perm_identity,
    );
    final completeProcessingBtn = fcsButton(
      context,
      getLocalString(context, 'package.edit.complete.process.btn'),
      callack: _completeProcessing,
    );
    final descBox = InputText(
        labelTextKey: 'package.edit.desc',
        iconData: MaterialCommunityIcons.message_text_outline,
        controller: _descCtl);
    final remarkBox = InputText(
        labelTextKey: 'package.edit.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,
            "package.edit.title",
            fontSize: 20,
            color: primaryColor,
          ),
          actions: [
            IconButton(
              icon: Icon(Icons.delete, color: primaryColor),
              onPressed: _delete,
            )
          ],
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: ListView(
            children: [
              trackingIdBox,
              customerNameBox,
              statusBox,
              Divider(),
              Center(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: LocalText(
                    context,
                    "package.edit.procseeing",
                    color: primaryColor,
                    fontSize: 16,
                    fontWeight: FontWeight.w700,
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 18.0, right: 10),
                child: Column(
                  children: [
                    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 Row(
      children: [
        Padding(
          padding: const EdgeInsets.only(right: 18.0),
          child: LocalText(
            context,
            "package.create.market",
            color: primaryColor,
            fontSize: 16,
          ),
        ),
        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;
                }
                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;
    }
    setState(() {
      _isLoading = true;
    });
    PackageModel packageModel =
        Provider.of<PackageModel>(context, listen: false);
    try {
      _package.desc = _descCtl.text;
      _package.remark = _remarkCtl.text;
      _package.market = selectedMarket;
      // await packageModel.completeProcessing(_package,
      //     multiImgController.getAddedFile, multiImgController.getDeletedUrl);
      Navigator.pop(context);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  _delete() {
    showConfirmDialog(context, "package.delete.confirm", _deletePackage);
  }

  _deletePackage() async {
    setState(() {
      _isLoading = true;
    });
    PackageModel packageModel =
        Provider.of<PackageModel>(context, listen: false);
    try {
      // await packageModel.deletePackage(_package);
      Navigator.pop<bool>(context, true);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
