import 'package:fcs/domain/constants.dart';
import 'package:fcs/domain/entities/package.dart';
import 'package:fcs/domain/vo/delivery_address.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/delivery_address/model/delivery_address_model.dart';
import 'package:fcs/pages/main/model/main_model.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:fcs/pages/package/model/package_model.dart';
import 'package:fcs/pages/widgets/defalut_delivery_address.dart';
import 'package:fcs/pages/widgets/delivery_address_selection.dart';
import 'package:fcs/pages/widgets/display_text.dart';
import 'package:fcs/pages/widgets/fcs_id_icon.dart';
import 'package:fcs/pages/widgets/local_button.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:fcs/pages/widgets/status_tree.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';

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

class PackageInfo extends StatefulWidget {
  final isCustomer;
  final isSearchResult;
  final Package package;

  PackageInfo(
      {this.package, this.isSearchResult = false, this.isCustomer = false});

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

class _PackageInfoState extends State<PackageInfo> {
  var dateFormatter = new DateFormat('dd MMM yyyy');
  Package _package;
  bool _isLoading = false;
  MultiImgController multiImgController = MultiImgController();

  @override
  void initState() {
    super.initState();
    initPackage(widget.package);
  }

  initPackage(Package package) {
    setState(() {
      _package = package;
      multiImgController.setImageUrls = package.photoUrls;
    });
  }

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

  @override
  Widget build(BuildContext context) {
    String id = Provider.of<MainModel>(context).user.id;
    bool owner = _package.userID == id;
    bool canChangeDeliveryAddress =
        _package.status == package_received_status ||
            _package.status == package_processed_status;

    final trackingIdBox = DisplayText(
      text: _package.trackingID,
      labelTextKey: "package.tracking.id",
      iconData: MaterialCommunityIcons.barcode_scan,
    );
    var fcsIDBox = DisplayText(
      text: _package.fcsID,
      labelTextKey: "processing.fcs.id",
      icon: FcsIDIcon(),
    );
    final customerNameBox = DisplayText(
      text: _package.userName,
      labelTextKey: "package.create.name",
      iconData: Icons.perm_identity,
    );
    final marketBox = DisplayText(
      text: _package.market ?? "-",
      labelTextKey: "package.create.market",
      iconData: Icons.store,
    );
    final descBox = DisplayText(
      text: _package.desc ?? "-",
      labelTextKey: "package.edit.desc",
      iconData: MaterialCommunityIcons.message_text_outline,
    );
    final remarkBox = DisplayText(
      text: _package.remark ?? "-",
      labelTextKey: "package.edit.remark",
      iconData: Entypo.new_message,
    );
    final img = MultiImageFile(
      enabled: false,
      controller: multiImgController,
      title: "Receipt File",
    );

    final returnButton = LocalButton(
      textKey: "receiving.return.btn",
      callBack: _return,
    );
    final deliveryAddressBox = DefaultDeliveryAddress(
      deliveryAddress: _package.deliveryAddress,
      labelKey: "package.delivery.address",
      onTap: owner && canChangeDeliveryAddress
          ? () async {
              DeliveryAddress d = await Navigator.push<DeliveryAddress>(
                context,
                CupertinoPageRoute(
                    builder: (context) => DeliveryAddressSelection(
                          deliveryAddress: _package.deliveryAddress,
                        )),
              );
              if (d == null) return;
              _changeDeliverayAddress(d);
            }
          : null,
    );

    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.info.title",
            fontSize: 20,
            color: primaryColor,
          ),
        ),
        body: Card(
          child: Column(
            children: <Widget>[
              Expanded(
                  child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: ListView(children: <Widget>[
                  trackingIdBox,
                  widget.isSearchResult ? Container() : fcsIDBox,
                  widget.isSearchResult ? Container() : customerNameBox,
                  widget.isSearchResult ? Container() : marketBox,
                  _package.photoUrls.length == 0 ? Container() : img,
                  widget.isSearchResult ? Container() : descBox,
                  remarkBox,
                  _package.status == package_received_status &&
                          widget.isCustomer
                      ? returnButton
                      : Container(),
                  widget.isSearchResult ? Container() : deliveryAddressBox,
                  widget.isSearchResult
                      ? Container()
                      : StatusTree(
                          shipmentHistory: _package.shipmentHistory,
                          currentStatus: _package.status),
                  SizedBox(
                    height: 20,
                  )
                ]),
              )),
            ],
          ),
        ),
      ),
    );
  }

  _changeDeliverayAddress(DeliveryAddress deliveryAddress) async {
    if (deliveryAddress == null) return;
    setState(() {
      _isLoading = true;
    });
    PackageModel packageModel =
        Provider.of<PackageModel>(context, listen: false);
    DeliveryAddressModel deliveryAddressModel =
        Provider.of<DeliveryAddressModel>(context, listen: false);

    try {
      await packageModel.changeDeliveryAddress(_package, deliveryAddress);
      var da =
          await deliveryAddressModel.getDeliveryAddress(deliveryAddress.id);
      setState(() {
        _package.deliveryAddress = da;
      });
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  _return() {
    showConfirmDialog(context, "receiving.return.confirm", _returnReceiving);
  }

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