import 'package:farm_tpf/utils/const_style.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:farm_tpf/utils/formatter.dart';
import 'package:get/get.dart';
import 'package:get/state_manager.dart';

class WidgetFieldDateTimePicker extends StatefulWidget {
  final DateTime initDateTime;
  final Function(DateTime selectedDateTimeLocal) onUpdateDateTime;
  WidgetFieldDateTimePicker({required this.initDateTime, required this.onUpdateDateTime});
  @override
  _WidgetFieldDateTimePickerState createState() => _WidgetFieldDateTimePickerState();
}

class _WidgetFieldDateTimePickerState extends State<WidgetFieldDateTimePicker> {
  var changeDate = Get.put(ChangeDateTimePicker());
  @override
  void initState() {
    super.initState();
    changeDate.initValue(selectedDate: widget.initDateTime);
    widget.onUpdateDateTime(changeDate.selectedDateTime);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ChangeDateTimePicker>(builder: (value) {
      return FlatButton(
          padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: 0.0, left: 0.0),
          onPressed: () {
            DatePicker.showDateTimePicker(context, showTitleActions: true, onChanged: (date) {}, onConfirm: (date) {
              changeDate.change(date);
              widget.onUpdateDateTime(date);
            }, currentTime: value.selectedDateTime, locale: LocaleType.vi);
          },
          child: Container(
              padding: const EdgeInsets.only(top: 0.0, right: 0.0, bottom: 10.5, left: 0.0),
              decoration: const BoxDecoration(
                border: kBorderTextField,
              ),
              child: Row(
                children: [
                  Expanded(
                      child: Text(
                    value.selectedDateTime.displayDateTime_DDMMYYYY_HHmm(),
                    style: const TextStyle(fontSize: 14.0, color: Colors.black87),
                  )),
                  const Icon(
                    Icons.date_range,
                    color: Colors.grey,
                  ),
                ],
              )));
    });
  }
}

class ChangeDateTimePicker extends GetxController {
  DateTime selectedDateTime = DateTime.now();
  initValue({DateTime? selectedDate}) {
    selectedDateTime = selectedDate ?? DateTime.now();
    update();
  }

  change(DateTime dateTime) {
    selectedDateTime = dateTime;
    update();
  }
}
