import 'package:farm_tpf/utils/const_style.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart' as datatTimePicker;
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 ?? DateTime.now());
  }

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

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

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