import 'package:calendar_date_picker2/calendar_date_picker2.dart';
import 'package:cims_apps/application/component/button/button_view.dart';
import 'package:cims_apps/application/component/text_form/text_form_view.dart';
import 'package:cims_apps/application/theme/color_palette.dart';
import 'package:cims_apps/core/utils/size_config.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class DatePickerView extends StatelessWidget {
  final String name;
  final TextEditingController ctrl;
  final DateTime? minDate, maxDate;
  final String? hintText, buttonName;
  final bool isMultipleSelection, enabled;
  final List<DateTime>? initialValue;
  final ValueChanged<OnChangedDatePickerModel>? onChanged;
  final ValueChanged<List<DateTime?>>? onFinish;
  final FormFieldValidator<String>? validatorDate;
  const DatePickerView(
      {Key? key,
      required this.name,
      required this.ctrl,
      this.minDate,
      this.maxDate,
      this.hintText,
      this.buttonName,
      required this.isMultipleSelection,
      required this.enabled,
      this.initialValue,
      this.onChanged,
      this.onFinish,
      this.validatorDate})
      : super(key: key);

  String _dateFormat(DateTime? dateTime) =>
      dateTime != null ? DateFormat('dd/MM/yyyy').format(dateTime) : "";

  @override
  Widget build(BuildContext context) {
    List<DateTime?> initData = initialValue ?? [];
    List<DateTime?> dateList = [];

    String dateLabel() {
      return dateList.map((e) => _dateFormat(e)).join(" - ");
    }

    onChangedDatePicker(List<DateTime?> value) {
      if (isMultipleSelection) {
        final pickerDateRange = PickerDateRange(
          startDate: value[0] ?? DateTime.now(),
          endDate:
              value.length > 1 ? value[1] ?? DateTime.now() : DateTime.now(),
        );
        onChanged
            ?.call(OnChangedDatePickerModel(pickerDateRange: pickerDateRange));
      } else {
        onChanged?.call(OnChangedDatePickerModel(dateTime: value[0]));
      }
      dateList = value;
    }

    dialogDatePicker() {
      showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        builder: (BuildContext context) {
          return Container(
            padding: const EdgeInsets.only(top: 16.0),
            height: SizeConfig.height * .65,
            child: Column(
              // mainAxisAlignment: MainAxisAlignment.spaceBetween,
              mainAxisSize: MainAxisSize.min,
              children: [
                CalendarDatePicker2(
                  value: [...initData],
                  config: CalendarDatePicker2Config(
                    centerAlignModePicker: true,
                    calendarType: isMultipleSelection
                        ? CalendarDatePicker2Type.range
                        : CalendarDatePicker2Type.single,
                    customModePickerIcon: const SizedBox(),
                    firstDate: minDate ?? DateTime(1900),
                    lastDate: maxDate,
                  ),
                  // initialValue: [...initData],
                  onValueChanged: (value) {
                    onChangedDatePicker(value);
                  },
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: ButtonView(
                    width: SizeConfig.width,
                    onPressed: () {
                      if (dateList.isNotEmpty) {
                        onFinish?.call(dateList);
                        ctrl.text = dateLabel();
                        initData = dateList;
                      }
                      Navigator.pop(context);
                    },
                    name: 'OK',
                  ),
                ),
              ],
            ),
          );
        },
      );
    }

    return TextFormView(
      name: name,
      hintText: hintText,
      readOnly: true,
      ctrl: ctrl,
      validator: validatorDate,
      enabled: enabled,
      onTap: () {
        if (enabled) dialogDatePicker();
      },
      suffixIcon: const UnconstrainedBox(
        child: Icon(
          Icons.calendar_today_rounded,
          color: ColorPalette.slate400,
        ),
      ),
    );
  }
}

class OnChangedDatePickerModel {
  final DateTime? dateTime;
  final PickerDateRange? pickerDateRange;

  OnChangedDatePickerModel({this.dateTime, this.pickerDateRange});
}

class PickerDateRange {
  final DateTime startDate;
  final DateTime endDate;

  PickerDateRange({required this.startDate, required this.endDate});
}
