import 'package:fcs/domain/entities/package.dart';
import 'package:fcs/domain/entities/processing.dart';
import 'package:fcs/domain/entities/user.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:fcs/pages/package/package_info.dart';
import 'package:fcs/pages/user_search/user_serach.dart';
import 'package:fcs/pages/widgets/display_text.dart';
import 'package:fcs/pages/widgets/fcs_id_icon.dart';
import 'package:fcs/pages/widgets/local_text.dart';
import 'package:fcs/pages/widgets/progress.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_vector_icons/flutter_vector_icons.dart';
import 'package:provider/provider.dart';

import 'model/processing_model.dart';
import 'package_editor.dart';

class ProcesingEditor extends StatefulWidget {
  final Processing? processing;
  const ProcesingEditor({this.processing});
  @override
  _ProcesingEditorState createState() => _ProcesingEditorState();
}

class _ProcesingEditorState extends State<ProcesingEditor> {
  Processing processing = Processing();
  bool _isLoading = false;
  late bool _isNew;
  User? consignee;
  User? sender;
  List<Package> packages = [];

  @override
  void initState() {
    super.initState();
    _isNew = widget.processing == null;
    if (!_isNew) {
      processing = widget.processing!;
      consignee = User(
          fcsID: processing.userID,
          name: processing.userName,
          phoneNumber: processing.userPhoneNumber);
      sender = User(
          fcsID: processing.fcsID,
          name: processing.shipperName,
          phoneNumber: processing.shipperPhoneNumber);
      packages = processing.packages;
    }
  }

  @override
  Widget build(BuildContext context) {
    var fcsIDBox = Row(
      children: <Widget>[
        Expanded(
            child: DisplayText(
          text: consignee != null ? consignee!.fcsID : "",
          labelTextKey: "processing.fcs.id",
          icon: FcsIDIcon(),
        )),
        IconButton(
            icon: Icon(Icons.search, color: primaryColor),
            onPressed: () => searchUser(context, onUserSelect: (u) {
                  setState(() {
                    this.consignee = u;
                  });
                }, popPage: true)),
      ],
    );

    final phoneNumberBox = DisplayText(
      text: consignee != null ? consignee!.phoneNumber : "",
      labelTextKey: "processing.phone",
      maxLines: 2,
      iconData: Icons.phone,
    );

    final namebox = DisplayText(
      text: consignee != null ? consignee!.name : "",
      labelTextKey: "processing.consignee.name",
      maxLines: 2,
      iconData: Icons.person,
    );

    final consigneeBox = Container(
      child: Column(
        children: [
          fcsIDBox,
          phoneNumberBox,
          namebox,
        ],
      ),
    );

    var shipperIDBox = Row(
      children: <Widget>[
        Expanded(
            child: DisplayText(
          text: sender != null ? sender!.fcsID : "",
          labelTextKey: "processing.fcs.id",
          icon: FcsIDIcon(),
        )),
        IconButton(
            icon: Icon(Icons.search, color: primaryColor),
            onPressed: () => searchUser(context, onUserSelect: (u) {
                  setState(() {
                    this.sender = u;
                  });
                }, popPage: true)),
      ],
    );

    final shipperPhoneNumberBox = DisplayText(
      text: sender != null ? sender!.phoneNumber : "",
      labelTextKey: "processing.phone",
      maxLines: 2,
      iconData: Icons.phone,
    );

    final shipperNamebox = DisplayText(
      text: sender != null ? sender!.name : "",
      labelTextKey: "processing.shipper.name",
      maxLines: 2,
      iconData: Icons.person,
    );

    final shipperBox = Container(
      child: Column(
        children: [
          shipperIDBox,
          shipperPhoneNumberBox,
          shipperNamebox,
        ],
      ),
    );

    final packageTitleBox = Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Text("Packages (${packages.length})"),
          IconButton(
              icon: Icon(
                Icons.add_circle,
                color: primaryColor,
              ),
              onPressed: () async {
                if (this.consignee == null) {
                  showMsgDialog(
                      context, "Warning", "Please select 'Consignee'");
                  return;
                }
                Package? _package = await Navigator.push<Package>(
                  context,
                  CupertinoPageRoute(
                      builder: (context) => PackageEditor(
                            sender: this.sender,
                            consignee: this.consignee,
                          )),
                );
                _addPackage(_package!);
                // _savePackage(_package);
              }),
        ],
      ),
    );

    final createButton = fcsButton(
      context,
      getLocalString(context, 'processing.edit.complete.btn'),
      callack: _save,
    );

    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,
              _isNew ? "processing.create" : "processing.update",
              fontSize: 20,
              color: primaryColor,
            ),
          ),
          body: Padding(
            padding: const EdgeInsets.only(left: 12.0, right: 12),
            child: ListView(
              children: <Widget>[
                SizedBox(
                  height: 10,
                ),
                Row(
                  children: [
                    Flexible(child: consigneeBox),
                    Flexible(child: shipperBox)
                  ],
                ),
                Divider(),
                packageTitleBox,
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: _getPackages(context, packages),
                ),
                SizedBox(
                  height: 20,
                ),
                createButton,
                SizedBox(
                  height: 10,
                ),
              ],
            ),
          ),
        ));
  }

  List<Widget> _getPackages(BuildContext context, List<Package> packages) {
    return packages.map((p) {
      return InkWell(
        onTap: () async {
          Package? _package = await Navigator.of(context).push<Package>(
              CupertinoPageRoute(
                  builder: (context) => PackageInfo(package: p)));
          _savePackage(_package!);
        },
        child: DisplayText(
          labelTextKey: "processing.tracking.id",
          iconData: MaterialCommunityIcons.barcode_scan,
          text: p.trackingID,
        ),
      );
    }).toList();
  }

  _addPackage(Package package) {
    if (package == null) return;

    this.packages.add(package);
    setState(() {});
  }

  _savePackage(Package package) {
    if (package == null) return;
    setState(() {});
  }

  _removePackage(Package package) {
    if (package == null) return;
    this.packages.removeWhere((p) => p.trackingID == package.trackingID);
    setState(() {});
  }

  _save() async {
    setState(() {
      _isLoading = true;
    });

    ProcessingModel processingModel =
        Provider.of<ProcessingModel>(context, listen: false);
    try {
      if (_isNew) {
        await processingModel.createProcessing(processing);
      } else {
        processing.id = widget.processing!.id;
        await processingModel.updateProcessing(processing);
      }
      Navigator.pop(context);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
}
