import 'package:fcs/domain/constants.dart';
import 'package:fcs/domain/entities/market.dart';
import 'package:fcs/domain/entities/package.dart';
import 'package:fcs/domain/entities/user.dart';
import 'package:fcs/helpers/theme.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/main/util.dart';
import 'package:fcs/pages/package_search/package_serach.dart';
import 'package:fcs/pages/widgets/barcode_scanner.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_vector_icons/flutter_vector_icons.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';

class PackageEditor extends StatefulWidget {
  final Package? package;
  final User? consignee;
  final User? sender;
  PackageEditor({this.package, this.consignee, this.sender});

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

class _PackageEditorState extends State<PackageEditor> {
  TextEditingController _remarkCtl = new TextEditingController();
  TextEditingController _descCtl = new TextEditingController();

  bool _isLoading = false;
  MultiImgController multiImgController = MultiImgController();
  Package? _package;

  @override
  void initState() {
    super.initState();
    _package = Package();
    _loadPackageData(widget.package?.id!);
  }

  _loadPackageData(String? id) async {
    if (id != null) {
      PackageModel packageModel =
          Provider.of<PackageModel>(context, listen: false);
      Package? package = await packageModel.getPackage(id);
      if (package != null) {
        if (package.status != package_received_status) {
          showMsgDialog(context, "Error",
              "Invalid package status, expected '$package_received_status' status");
          return;
        }
        setState(() {
          _package = package;
        });
      }
    }
    setState(() {
      selectedMarket = _package!.market ?? "";
      _descCtl.text = _package!.desc!;
      _remarkCtl.text = _package!.remark!;
      multiImgController.setImageUrls = _package!.photoUrls;
    });
  }

  @override
  Widget build(BuildContext context) {
    var trackingIDBox = Row(
      children: <Widget>[
        Expanded(
            child: DisplayText(
          text: _package!.trackingID != null ? _package!.trackingID : "",
          labelTextKey: "processing.tracking.id",
          iconData: MaterialCommunityIcons.barcode_scan,
        )),
        IconButton(
            icon: Icon(Icons.search, color: primaryColor),
            onPressed: () => searchPackage(context, callbackPackageSelect: (u) {
                  _loadPackageData(u.id!);
                  Navigator.pop(context);
                })),
      ],
    );

    final descBox = InputText(
        labelTextKey: 'processing.desc',
        iconData: MaterialCommunityIcons.message_text_outline,
        controller: _descCtl);

    final remarkBox = InputText(
        labelTextKey: 'processing.remark',
        iconData: Entypo.new_message,
        controller: _remarkCtl);

    final img = MultiImageFile(
      enabled: true,
      controller: multiImgController,
      title: "Receipt File",
    );

    final selectBtn = fcsButton(
      context,
      getLocalString(context, 'processing.package.select.btn'),
      callack: _selectPackage,
    );
    return LocalProgress(
      inAsyncCall: _isLoading,
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          leading: new IconButton(
            icon: new Icon(CupertinoIcons.back, color: primaryColor, size: 30),
            onPressed: () {
              if (isDataChanged()) {
                showConfirmDialog(context, "back.button_confirm", () {
                  Navigator.of(context).pop();
                });
              } else {
                Navigator.of(context).pop();
              }
            },
          ),
          shadowColor: Colors.transparent,
          backgroundColor: Colors.white,
          title: widget.package == null
              ? LocalText(
                  context,
                  "processing.package.create",
                  fontSize: 20,
                  color: primaryColor,
                )
              : LocalText(
                  context,
                  "processing.package.update",
                  fontSize: 20,
                  color: primaryColor,
                ),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: ListView(
            children: [
              trackingIDBox,
              SizedBox(
                height: 10,
              ),
              img,
              Divider(),
              SizedBox(
                height: 15,
              ),
              marketDropdown(),
              descBox,
              remarkBox,
              SizedBox(
                height: 20,
              ),
              selectBtn,
              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(left: 0, right: 10),
          child: Icon(Icons.store, color: primaryColor),
        ),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: const EdgeInsets.only(right: 18.0),
                child: LocalText(
                  context,
                  "processing.market",
                  color: Colors.black54,
                  fontSize: 16,
                ),
              ),
              DropdownButton<String>(
                isDense: true,
                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()),
    );
  }

  _selectPackage() async {
    setState(() {
      _isLoading = true;
    });
    PackageModel packageModel =
        Provider.of<PackageModel>(context, listen: false);
    try {
      _package!.market = selectedMarket!;
      _package!.desc = _descCtl.text;
      _package!.remark = _remarkCtl.text;
      _package!.photoFiles = multiImgController.getUpdatedFile;
      _package!.fcsID = widget.consignee!.fcsID;
      _package!.senderFCSID =
          widget.sender!.fcsID != null ? widget.sender!.fcsID : "";

      await packageModel.updateProcessing(_package!,
          multiImgController.getAddedFile, multiImgController.getDeletedUrl);

      Navigator.pop<Package>(context, _package);
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  isDataChanged() {
    return selectedMarket != null ||
        _descCtl.text != "" ||
        _remarkCtl.text != "" ||
        multiImgController.getAddedFile.isNotEmpty;
  }
}
