import 'package:fcs/domain/entities/package.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/main/model/main_model.dart';
import 'package:fcs/pages/package/model/package_model.dart';
import 'package:fcs/pages/widgets/bottom_up_page_route.dart';
import 'package:fcs/pages/widgets/display_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/material.dart';
import 'package:flutter_icons/flutter_icons.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:timeline_list/timeline.dart';
import 'package:timeline_list/timeline_model.dart';

import 'processing_editor.dart';

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

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

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

class _ProcessingInfoState extends State<ProcessingInfo> {
  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) {
    bool isCustomer = Provider.of<MainModel>(context).isCustomer();

    final trackingIdBox = DisplayText(
      text: _package.trackingID,
      labelTextKey: "processing.tracking.id",
      iconData: MaterialCommunityIcons.barcode_scan,
    );
    final customerNameBox = DisplayText(
      text: _package.userName,
      labelTextKey: "processing.name",
      iconData: Icons.perm_identity,
    );
    final statusBox = DisplayText(
      text: _package.currentStatus,
      labelTextKey: "processing.status",
      iconData: AntDesign.exclamationcircleo,
    );
    final marketBox = DisplayText(
      text: _package.market ?? "-",
      labelTextKey: "processing.market",
      iconData: Icons.store,
    );
    final descBox = DisplayText(
      text: _package.desc ?? "-",
      labelTextKey: "processing.desc",
      iconData: MaterialCommunityIcons.message_text_outline,
    );
    final remarkBox = DisplayText(
      text: _package.remark ?? "-",
      labelTextKey: "processing.remark",
      iconData: Entypo.new_message,
    );
    final img = MultiImageFile(
      enabled: false,
      controller: multiImgController,
      title: "Receipt File",
    );

    return LocalProgress(
      inAsyncCall: _isLoading,
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          leading: new IconButton(
            icon: new Icon(Icons.close, color: primaryColor, size: 30),
            onPressed: () => Navigator.of(context).pop(),
          ),
          shadowColor: Colors.transparent,
          backgroundColor: Colors.white,
          title: LocalText(
            context,
            "processing.info.title",
            fontSize: 20,
            color: primaryColor,
          ),
          actions: <Widget>[
            isCustomer
                ? Container()
                : IconButton(
                    icon: Icon(Icons.edit, color: primaryColor),
                    onPressed: _gotoEditor,
                  )
          ],
        ),
        body: Card(
          child: Column(
            children: <Widget>[
              Expanded(
                  child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: ListView(children: <Widget>[
                  trackingIdBox,
                  customerNameBox,
                  marketBox,
                  statusBox,
                  _package.photoUrls.length == 0 ? Container() : img,
                  descBox,
                  remarkBox,
                  ExpansionTile(
                    initiallyExpanded: true,
                    title: Text(
                      'Status',
                      style: TextStyle(
                          color: primaryColor, fontWeight: FontWeight.bold),
                    ),
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.only(left: 20),
                        height: 400,
                        child: Timeline(
                            children: _models(),
                            position: TimelinePosition.Left),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 20,
                  )
                ]),
              )),
            ],
          ),
        ),
      ),
    );
  }

  List<TimelineModel> _models() {
    if (_package.shipmentHistory == null) return [];
    return _package.shipmentHistory
        .map((e) => TimelineModel(
            Padding(
              padding: const EdgeInsets.all(18.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(e.status,
                      style: TextStyle(
                          color: e.done ? primaryColor : Colors.grey,
                          fontSize: 16,
                          fontWeight: FontWeight.bold)),
                  Text(dateFormat.format(e.date)),
                ],
              ),
            ),
            iconBackground: e.done ? primaryColor : Colors.grey,
            icon: Icon(
              e.status == "shipped"
                  ? Ionicons.ios_airplane
                  : e.status == "delivered"
                      ? MaterialCommunityIcons.truck_fast
                      : e.status == "processed"
                          ? MaterialIcons.check
                          : Octicons.package,
              color: Colors.white,
            )))
        .toList();
  }

  _gotoEditor() async {
    bool deleted = await Navigator.push<bool>(
        context,
        BottomUpPageRoute(ProcessingEditor(
          package: widget.package,
        )));
    if (deleted ?? false) {
      Navigator.pop(context);
    } else {
      PackageModel packageModel =
          Provider.of<PackageModel>(context, listen: false);
      Package p = await packageModel.getPackage(_package.id);
      initPackage(p);
    }
  }
}
