import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/UI/Template/CupertinoPicker/Bloc/date_pick_bloc.dart';
import 'package:absenkuv3/UI/Template/CupertinoPicker/UI/CustomCupertinoDatePicker.dart';
import 'package:absenkuv3/UI/Template/DateRangePicker/Bloc/DateRangePickerBloc.dart';
import 'package:absenkuv3/UI/Template/MonthPicker/Bloc/MonthPickerBloc.dart'
    as monthPicker;
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:absenkuv3/UI/Template/templateButton.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';

// ignore: must_be_immutable
class TemplateNewDateRangePicker extends StatefulWidget {
  List<DateTime>? initialData;
  double height;
  DateTime? firstDate;
  DateTime? lastDate;
  TemplateNewDateRangePicker(
      {this.initialData, this.height = 46, this.firstDate, this.lastDate}) {
    firstDate = firstDate ?? DateTime(DateTime.now().year - 2);
    lastDate = lastDate ??
        DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day);
  }
  @override
  _TemplateNewDateRangePickerState createState() =>
      _TemplateNewDateRangePickerState();
}

class _TemplateNewDateRangePickerState
    extends State<TemplateNewDateRangePicker> {
  DateTime selectedDate = DateTime.now();
  final dateFormat = new DateFormat('dd-MM-yyyy');
  DateTime? maxDate;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: PengaturanBahasa().getDataBahasa(),
        builder: (context, snapshot) {
          return BlocBuilder<DateRangePickerBloc, DateRangePickerState>(
            builder: (BuildContext context,
                DateRangePickerState dateRangePickerState) {
              print(dateRangePickerState);
              String labelstart = '-';
              String labelend = '-';
              DateTime startDate = DateTime(DateTime.now().year,
                  DateTime.now().month, DateTime.now().day);
              DateTime endDate = DateTime(DateTime.now().year,
                  DateTime.now().month, DateTime.now().day);
              if (dateRangePickerState is DateAvailable) {
                labelstart =
                    '${dateFormat.format(dateRangePickerState.date[0])}';
                labelend = '${dateFormat.format(dateRangePickerState.date[1])}';
                startDate = dateRangePickerState.date[0];
                endDate = dateRangePickerState.date[1];
              }
              return Row(
                children: [
                  Expanded(
                    child: GestureDetector(
                      onTap: () async {
                        // final currentState =
                        //     BlocProvider.of<DateRangePickerBloc>(context).date;
                        custom(context, true, widget.firstDate!);
                      },
                      child: Column(
                        children: [
                          Container(
                            padding: EdgeInsets.fromLTRB(0, 7, 15, 7),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  snapshot.data == null
                                      ? "Mulai Dari"
                                      : snapshot.data == 'id'
                                          ? "Mulai Dari"
                                          : "Start Date",
                                  style: TextStyle(
                                      color: Colors.grey.shade600,
                                      fontWeight: FontWeight.w400,
                                      fontSize: CustomStyle.fontSizeSmall - 1),
                                ),
                                SizedBox(
                                  height: 11,
                                ),
                                // Row(
                                //   mainAxisAlignment: MainAxisAlignment.center,
                                //   children: [
                                //     SizedBox(width: 8,),
                                //     Text(label, style: TextStyle(fontSize: CustomStyle.fontSizeSmall-1, color: Colors.white),),
                                //     SizedBox(width: 4,),
                                //     Icon(Icons.keyboard_arrow_down, color: Colors.white,  size: 18)
                                //   ],
                                // ),
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    // SizedBox(width: 8,),
                                    Container(
                                        margin:
                                            EdgeInsets.only(left: 0, right: 4),
                                        child: Text(
                                          labelstart,
                                          style: TextStyle(
                                              fontSize:
                                                  CustomStyle.fontSizeSmall - 1,
                                              color: Colors.black),
                                        )),
                                    // SizedBox(width: 4,),
                                    Icon(Icons.keyboard_arrow_down,
                                        color: Colors.black, size: 18)
                                  ],
                                ),
                              ],
                            ),
                          ),
                          Divider(
                            thickness: 0.5,
                            height: 1,
                          )
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 20,
                  ),
                  Expanded(
                    child: GestureDetector(
                      onTap: () async {
                        final currentState =
                            BlocProvider.of<DateRangePickerBloc>(context).date;
                        custom(context, false, currentState.first);
                        // BlocProvider.of<monthPicker.MonthPickerBloc>(context).add(monthPicker.SetDate(null)); //RESET MONTH
                        // final DateTimeRange? picked = await showDateRangePicker(
                        //     context: context,
                        //     firstDate: widget.firstDate!,
                        //     lastDate: widget.lastDate!,
                        //     locale: Locale(snapshot.data??'en'),
                        //     saveText: snapshot.data == null ? 'TERAPKAN' : snapshot.data == 'id' ? 'TERAPKAN' : 'APPLY',
                        //     initialDateRange: DateTimeRange(
                        //         start: startDate,
                        //         end: endDate
                        //     ));
                        // if (picked != null) BlocProvider.of<DateRangePickerBloc>(context).add(SetDate([picked.start, picked.end]));
                      },
                      child: Column(
                        children: [
                          Container(
                            padding: EdgeInsets.fromLTRB(0, 7, 15, 7),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  snapshot.data == null
                                      ? "Sampai"
                                      : snapshot.data == 'id'
                                          ? "Sampai"
                                          : "End Date",
                                  style: TextStyle(
                                      color: Colors.grey.shade600,
                                      fontWeight: FontWeight.w400,
                                      fontSize: CustomStyle.fontSizeSmall - 1),
                                ),
                                SizedBox(
                                  height: 11,
                                ),
                                // Row(
                                //   mainAxisAlignment: MainAxisAlignment.center,
                                //   children: [
                                //     SizedBox(width: 8,),
                                //     Text(label, style: TextStyle(fontSize: CustomStyle.fontSizeSmall-1, color: Colors.white),),
                                //     SizedBox(width: 4,),
                                //     Icon(Icons.keyboard_arrow_down, color: Colors.white,  size: 18)
                                //   ],
                                // ),
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    // SizedBox(width: 8,),
                                    Container(
                                        margin:
                                            EdgeInsets.only(left: 0, right: 4),
                                        child: Text(
                                          labelend,
                                          style: TextStyle(
                                              fontSize:
                                                  CustomStyle.fontSizeSmall - 1,
                                              color: Colors.black),
                                        )),
                                    // SizedBox(width: 4,),
                                    Icon(Icons.keyboard_arrow_down,
                                        color: Colors.black, size: 18)
                                  ],
                                ),
                              ],
                            ),
                          ),
                          Divider(
                            thickness: 0.5,
                            height: 1,
                          )
                        ],
                      ),
                    ),
                  ),
                ],
              );
            },
          );
        });
  }

  void custom(
      BuildContext context, bool isStartDate, DateTime initialDateTime) {
    final currentState = BlocProvider.of<DateRangePickerBloc>(context).date;
    print(currentState);
    print("kondisi start date ${isStartDate}");
    DateTime? minimumDate;
    DateTime? minimumDateIsStart;
    DateTime? position;

    print(initialDateTime);

    minimumDateIsStart = initialDateTime;
    // if (currentState is DateSelected) {
    if (isStartDate) {
      initialDateTime = currentState.first;
      position = currentState.first;
    } else {
      minimumDate = currentState.first;
      print("ini minimum date ${minimumDate}");
      initialDateTime = currentState.first.isAfter(DateTime.now())
          ? currentState.first
          : DateTime.now();
      position = DateTime.now();
    }
    // }
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      isScrollControlled: true,
      builder: (context) {
        DateTime selectedDateTime = initialDateTime;
        return FutureBuilder(
          future: PengaturanBahasa().getDataBahasa(),
          builder: (BuildContext context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return Container(
                  child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    height: 5,
                    width: 50,
                    margin: EdgeInsets.symmetric(horizontal: 10, vertical: 15),
                    decoration: BoxDecoration(
                        color: Colors.grey,
                        borderRadius: BorderRadius.circular(10)),
                  ),
                  Divider(),
                  SizedBox(
                    height: 300,
                    child: CustomCupertinoDatePicker(
                      itemExtent: 50,
                      minDate: isStartDate ? minimumDateIsStart : minimumDate,
                      selectedDate: isStartDate ? position : initialDateTime,
                      bahasa: snapshot.data,
                      maxDate: DateTime.now(),
                      selectionOverlay: Container(
                        width: double.infinity,
                        height: 50,
                        decoration: const BoxDecoration(
                          border: Border.symmetric(
                            horizontal:
                                BorderSide(color: Colors.grey, width: 1),
                          ),
                        ),
                      ),
                      selectedStyle: const TextStyle(
                        color: Colors.blue,
                        fontWeight: FontWeight.w600,
                        fontSize: 24,
                      ),
                      unselectedStyle: TextStyle(
                        color: Colors.black,
                        fontWeight: FontWeight.w600,
                        fontSize: 18,
                      ),
                      disabledStyle: TextStyle(
                        color: Colors.grey[500],
                        fontSize: 18,
                      ),
                      onSelectedItemChanged: (date) {
                        selectedDateTime = date;
                      },
                    ),
                  ),
                  Divider(),
                  Container(
                    width: MediaQuery.sizeOf(context).width,
                    margin: EdgeInsets.all(10),
                    child: TemplateButton(
                      label: snapshot.data == 'id' ? "Terapkan" : 'Apply',
                      heightButton: 45,
                      fontSize: 15,
                      color: CustomStyle.color1,
                      widthButton: MediaQuery.of(context).size.width - 20,
                      onClick: () {
                        if (isStartDate) {
                          final endDateState =
                              BlocProvider.of<DateRangePickerBloc>(context)
                                  .date;
                          final updatedEndDate =
                              endDateState.last.isBefore(selectedDateTime)
                                  ? selectedDateTime
                                  : endDateState.last;
                          BlocProvider.of<DateRangePickerBloc>(context)
                              .add(SetDate([selectedDateTime, updatedEndDate]));
                        } else {
                          BlocProvider.of<DateRangePickerBloc>(context).add(
                              SetDate([currentState.first, selectedDateTime]));
                        }
                        Navigator.pop(context);
                      },
                    ),
                  )
                ],
              ));
            } else {
              return Container();
            }
          },
        );
      },
    );
  }
}
