import 'package:fcs/domain/constants.dart';
import 'package:fcs/domain/entities/package.dart';
import 'package:fcs/domain/entities/shipment.dart';
import 'package:fcs/domain/entities/user.dart';
import 'package:fcs/domain/vo/message.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/chat/model/message_model.dart';
import 'package:fcs/pages/customer/customer_editor.dart';
import 'package:fcs/pages/customer/model/customer_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/package/package_info.dart';
import 'package:fcs/pages/profile/profile_page.dart';
import 'package:fcs/pages/shipment/model/shipment_model.dart';
import 'package:fcs/pages/shipment/shipment_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'bubble.dart';

class MessageDetail extends StatelessWidget {
  final String receiverName;
  final String receiverID;
  final MessageModel messageModel;
  final TextEditingController textEditingController = TextEditingController();
  final ScrollController listScrollController = ScrollController();

  MessageDetail(
      {Key key, this.messageModel, this.receiverName, this.receiverID})
      : super(key: key) {
    listScrollController.addListener(() {
      if (listScrollController.offset >=
              listScrollController.position.maxScrollExtent &&
          !listScrollController.position.outOfRange) {
        if (!messageModel.isEnded) messageModel.load();
      }
      if (listScrollController.offset <=
              listScrollController.position.minScrollExtent &&
          !listScrollController.position.outOfRange) {}
    });
  }

  @override
  Widget build(BuildContext context) {
    String userID = Provider.of<MessageModel>(context).user.id;

    return Scaffold(
      appBar: AppBar(
        leading: new IconButton(
          icon: new Icon(CupertinoIcons.back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        backgroundColor: primaryColor,
        elevation: .9,
        title: Text(
          receiverName ?? "FCS Team",
        ),
        actions: <Widget>[],
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: [
            Expanded(
                child: ListView.builder(
              itemBuilder: (context, index) {
                var msg = messageModel.messages[index];
                Message next;
                bool showDate = false;
                if (messageModel.messages.length > index + 1) {
                  next = messageModel.messages[index + 1];
                  if (!msg.sameDay(next)) {
                    showDate = true;
                  }
                }
                if (messageModel.messages.length - 1 == index &&
                    messageModel.isEnded) {
                  showDate = true;
                }
                return buildBubble(
                    msg, userID, showDate, () => _viewDetail(context, msg));
              },
              itemCount: messageModel.messages.length,
              reverse: true,
              controller: listScrollController,
            )),
            buildInput(context),
          ],
        ),
      ),
    );
  }

  Widget buildBubble(Message msg, String userID, bool showDate,
      CallbackOnViewDetail callback) {
    return Bubble(
      message: msg.message,
      date: msg.date,
      delivered: true,
      sender: msg.senderName,
      isMine: msg.senderID == userID || msg.receiverID == receiverID,
      isCustomer: receiverID == null,
      showDate: showDate,
      isSystem: msg.messageType != null && msg.messageType != "",
      callbackOnViewDetail: callback,
    );
  }

  Widget buildInput(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(top: 3),
      child: Row(
        children: <Widget>[
          Flexible(
            child: Container(
              child: TextField(
                onSubmitted: (value) {
                  Provider.of<MessageModel>(context, listen: false)
                      .sendMessage(textEditingController.text, receiverID);
                  textEditingController.text = "";
                },
                style: TextStyle(color: primaryColor, fontSize: 15.0),
                maxLines: 10,
                minLines: 1,
                keyboardType: TextInputType.multiline,
                controller: textEditingController,
                decoration: InputDecoration(
                  focusedBorder: const OutlineInputBorder(
                    borderSide:
                        const BorderSide(color: primaryColor, width: 1.0),
                  ),
                  border: new OutlineInputBorder(
                    borderRadius: const BorderRadius.all(
                      const Radius.circular(10.0),
                    ),
                  ),
                  hintText: getLocalString(context, "message.hint.input"),
                  hintStyle: TextStyle(
                    color: Colors.grey,
                  ),
                ),
              ),
            ),
          ),

          // Button send message
          Material(
            child: Container(
              margin: EdgeInsets.symmetric(horizontal: 8.0),
              child: IconButton(
                icon: Icon(Icons.send),
                onPressed: () {
                  Provider.of<MessageModel>(context, listen: false)
                      .sendMessage(textEditingController.text, receiverID);
                  textEditingController.text = "";
                },
                color: primaryColor,
              ),
            ),
            color: Colors.white,
          ),
        ],
      ),
      width: double.infinity,
      decoration: BoxDecoration(
          border: Border(top: BorderSide(color: Colors.grey[700], width: 0.5)),
          color: Colors.white),
    );
  }

  _viewDetail(BuildContext context, Message message) async {
    if (message.messageType == message_type_package &&
        message.messageID != null &&
        message.messageID != "") {
      PackageModel packageModel =
          Provider.of<PackageModel>(context, listen: false);
      Package p = await packageModel.getPackage(message.messageID);
      if (p == null) return;
      Navigator.push<bool>(context,
          CupertinoPageRoute(builder: (context) => PackageInfo(package: p)));
    }
    if (message.messageType == message_type_profile &&
        message.messageID != null &&
        message.messageID != "") {
      MainModel mainModel = Provider.of<MainModel>(context, listen: false);

      if (mainModel.user.isCustomer()) {
        Navigator.push<bool>(
            context, CupertinoPageRoute(builder: (context) => Profile()));
      } else {
        CustomerModel customerModel =
            Provider.of<CustomerModel>(context, listen: false);
        User user = await customerModel.getUser(message.messageID);
        Navigator.of(context).push(CupertinoPageRoute(
            builder: (context) => CustomerEditor(customer: user)));
      }
    }
    if (message.messageType == message_type_shipment &&
        message.messageID != null &&
        message.messageID != "") {
      ShipmentModel shipmentModel =
          Provider.of<ShipmentModel>(context, listen: false);
      Shipment s = await shipmentModel.getShipment(message.messageID);
      if (s == null) return;
      await Navigator.push<bool>(
          context,
          CupertinoPageRoute(
              builder: (context) => ShipmentInfo(
                    shipment: s,
                    isCustomer: true,
                  )));
    }
  }
}
