import 'package:fcs/domain/entities/market.dart';
import 'package:fcs/domain/entities/package.dart';
import 'package:fcs/domain/entities/pickup.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/tracking_id_page.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:fcs/pages/pickup/model/pickup_model.dart';
import 'package:fcs/pages/widgets/defalut_delivery_address.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:intl/intl.dart';
import 'package:provider/provider.dart';

class PickupEditor extends StatefulWidget {
  final Pickup? pickup;

  const PickupEditor({Key? key, this.pickup}) : super(key: key);

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

class _PickupEditorState extends State<PickupEditor> {
  var dateFormatter = new DateFormat('dd MMM yyyy');
  var timeFormatter = new DateFormat('h:mm a');

  TextEditingController _remarkCtl = new TextEditingController();
  MultiImgController multiImgController = MultiImgController();

  Pickup? _pickup;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _pickup = widget.pickup;
    multiImgController.setImageUrls = _pickup!.photoUrls;
  }

  @override
  Widget build(BuildContext context) {
    final pickupNumberBox = DisplayText(
      text: _pickup!.pickupNumber ?? "",
      labelTextKey: "pickup.pickup_number",
      iconData: SimpleLineIcons.direction,
    );

    final pickupDateBox = DisplayText(
      text: _pickup!.pickupDate == null
          ? ""
          : dateFormatter.format(_pickup!.pickupDate!),
      labelTextKey: "pickup.date",
      iconData: Icons.date_range,
    );

    var timeBox = Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Container(
          width: 150,
          child: DisplayText(
            text: _pickup!.fromTime == null
                ? ""
                : timeFormatter.format(_pickup!.fromTime!),
            labelTextKey: "pickup.from_time",
            iconData: MaterialCommunityIcons.clock_start,
          ),
        ),
        Container(
          width: 150,
          child: DisplayText(
            text: _pickup!.toTime == null
                ? ""
                : timeFormatter.format(_pickup!.toTime!),
            labelTextKey: "pickup.to_time",
            iconData: MaterialCommunityIcons.clock_end,
          ),
        )
      ],
    );

    final customerBox = DisplayText(
      text: _pickup!.customerName ?? "",
      labelTextKey: "pickup.customer",
      iconData: Icons.perm_identity,
    );

    final staffNameBox = DisplayText(
      text: _pickup!.staffName ?? "",
      labelTextKey: "pickup.staff.name",
      iconData: Icons.perm_identity,
    );

    final deliveryAddressBox = DefaultDeliveryAddress(
        deliveryAddress: _pickup!.pickupAddress,
        labelKey: "pickup.delivery.address",
        onTap: null);

    final completeProcessingBtn = fcsButton(
      context,
      getLocalString(context, 'pickup.edit.complete.btn'),
      callack: _confirmComplete,
    );

    final completeRemarkBox = InputText(
        labelTextKey: 'pickup.complete.remark',
        iconData: Entypo.new_message,
        controller: _remarkCtl);

    final statusBox = DisplayText(
      text: _pickup != null ? _pickup!.status : "",
      labelTextKey: "pickup.status",
      iconData: Icons.av_timer,
    );

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

    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: LocalText(
            context,
            "pickup.edit.title",
            fontSize: 20,
            color: primaryColor,
          ),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: ListView(
            children: [
              pickupNumberBox,
              pickupDateBox,
              timeBox,
              customerBox,
              staffNameBox,
              statusBox,
              deliveryAddressBox,
              completeRemarkBox,
              img,
              _pickup!.status == "confirmed" || _pickup!.status == "rescheduled"
                  ? completeProcessingBtn
                  : Container(),
              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 Padding(
      padding: const EdgeInsets.only(left: 5.0, right: 0),
      child: 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()),
    );
  }

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

    try {
      _pickup?.completeRemark = _remarkCtl.text;
      await context.read<PickupModel>().complete(_pickup!,
          multiImgController.getAddedFile, multiImgController.getDeletedUrl);

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

  _confirmComplete() {
    showConfirmDialog(context, "pickup.confirm.complete", () {
      _completePickup();
    });
  }

  isDataChanged() {
    var _pickup = Pickup(
        completeRemark: _remarkCtl.text, photoUrls: widget.pickup!.photoUrls);
    return widget.pickup!.isChangedForEdit(_pickup) ||
        multiImgController.getAddedFile.isNotEmpty ||
        multiImgController.getDeletedUrl.isNotEmpty;
  }
}
