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/style.dart';
import 'package:absenkuv3/UI/Template/templateButton.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';

class DatePickCupertinoRange extends StatefulWidget {
  DatePickCupertinoRange({this.firstDate});

  final DateTime? firstDate;

  @override
  State<DatePickCupertinoRange> createState() => _DatePickCupertinoRangeState();
}

class _DatePickCupertinoRangeState extends State<DatePickCupertinoRange> {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: PengaturanBahasa().getDataBahasa(),
      builder: (BuildContext context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          String language = snapshot.data.toString();
          return BlocBuilder<DatePickBloc, DatePickState>(
            builder: (context, state) {
              DateTime? startDate;
              DateTime? endDate;
              TextEditingController startDateController =
                  TextEditingController();
              TextEditingController endDateController = TextEditingController();
              if (state is DateSelected) {
                startDate = state.startDate;
                endDate = state.endDate;
                startDateController.text = startDate == null
                    ? 'DD-MM-YYYY'
                    : DateFormat('dd-MM-yyyy').format(startDate);
                endDateController.text = endDate == null
                    ? 'DD-MM-YYYY'
                    : DateFormat('dd-MM-yyyy').format(endDate);
              }
              return Container(
                child: Row(
                  children: [
                    Expanded(
                      child: GestureDetector(
                        onTap: () async {
                          custom(context, true, widget.firstDate!);
                        },
                        child: 
                        TextFormField(
                          enabled: false,
                          style: TextStyle(color: Colors.black),
                          controller: startDateController,
                          decoration: InputDecoration(
                            enabledBorder: UnderlineInputBorder(
                                borderSide: BorderSide(
                              color: CustomStyle.colorLineFormTextField,
                            )),
                            disabledBorder: UnderlineInputBorder(
                                borderSide: BorderSide(
                                    color: CustomStyle.colorLineFormDropdown)),
                            fillColor: Colors.transparent,
                            isDense: true,
                            label: Row(
                              children: [
                                Text(
                                  language == 'id'
                                      ? 'Mulai dari'
                                      : 'Start date',
                                  style: TextStyle(
                                      color: Colors.grey, fontSize: 15),
                                ),
                                Container(
                                    margin: EdgeInsets.only(left: 5),
                                    child: Text("*",
                                        style: TextStyle(
                                            color: Colors.red,
                                            fontWeight: FontWeight.bold,
                                            fontSize: 15)))
                              ],
                            ),
                            hintText: startDate == null
                                ? 'DD-MM-YYYY'
                                : DateFormat('dd-MM-yyyy').format(startDate),
                            suffixIcon: Icon(
                              Icons.calendar_month_outlined,
                              size: 25,
                            ),
                            hintStyle: TextStyle(
                              fontSize: 13,
                              color: startDate == null
                                  ? Colors.grey[400]
                                  : Colors.black,
                            ),
                            // contentPadding: EdgeInsets.fromLTRB(3, 0, 13, 0),
                          ),
                        ),
                      
                      ),
                    ),
                    SizedBox(width: 30),
                    Expanded(
                      child: GestureDetector(
                        onTap: () async {
                          if (startDate == null) {
                          } else {
                            custom(context, false, startDate,initialDateTimeEnd: endDate);
                          }
                        },
                        child: TextFormField(
                          enabled: false,
                          controller: endDateController,
                          style: TextStyle(
                              color:
                                  endDate == null ? Colors.grey : Colors.black),
                          decoration: InputDecoration(
                            filled: true,
                            enabledBorder: UnderlineInputBorder(
                                borderSide: BorderSide(
                              color: CustomStyle.colorLineFormTextField,
                            )),
                            disabledBorder: UnderlineInputBorder(
                                borderSide: BorderSide(
                                    color: CustomStyle.colorLineFormDropdown)),
                            // fillColor: startDate == null ? Colors.grey.shade100 : Colors.white,
                            fillColor: Colors.transparent,
                            isDense: true,
                            label: Row(
                              children: [
                                Text(
                                  language == 'id' ? 'Sampai' : 'End date',
                                  style: TextStyle(
                                      color: startDate == null
                                          ? Colors.grey.withOpacity(0.4)
                                          : Colors.grey,
                                      fontSize: 15),
                                ),
                                startDate != null
                                    ? Container(
                                        margin: EdgeInsets.only(left: 5),
                                        child: Text("*",
                                            style: TextStyle(
                                                color: Colors.red,
                                                fontWeight: FontWeight.bold,
                                                fontSize: 15)))
                                    : Container()
                              ],
                            ),
                            hintText: endDate == null
                                ? 'DD-MM-YYYY'
                                : DateFormat('dd-MM-yyyy').format(endDate),
                            suffixIcon: Icon(
                              Icons.calendar_month_outlined,
                              size: 25,
                              color: startDate == null
                                  ? Colors.grey.withOpacity(0.4)
                                  : Colors.grey,
                            ),
                            hintStyle: TextStyle(
                              fontSize: 13,
                              color: startDate == null
                                  ? Colors.grey[400]
                                  : Colors.black,
                            ),
                            // contentPadding: EdgeInsets.fromLTRB(3, 0, 13, 0),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              );
            },
          );
        } else {
          return Container();
        }
      },
    );
  }

  void cupertinoPicker(
      BuildContext context, bool isStartDate, DateTime initialDateTime) {
    final currentState = BlocProvider.of<DatePickBloc>(context).state;
    DateTime? minimumDate;

    if (currentState is DateSelected) {
      if (isStartDate) {
        initialDateTime = currentState
            .startDate;
      } else {
        minimumDate = currentState.startDate;
        initialDateTime = currentState.startDate.isAfter(DateTime.now())
            ? currentState.startDate
            : DateTime.now();
      }
    }
    showCupertinoModalPopup(
      context: context,
      builder: (context) {
        DateTime selectedDateTime = initialDateTime;
        return Container(
          decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(topLeft: Radius.circular(20))),
          height: 340,
          child: Container(
              child: Column(
            children: [
              Container(
                margin: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
                width: 50,
                height: 7,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: Colors.grey.shade400,
                ),
              ),
              Divider(),
              CupertinoTheme(
                data: CupertinoThemeData(
                  brightness: Brightness.light,
                  textTheme: CupertinoTextThemeData(
                    dateTimePickerTextStyle: TextStyle(
                      color: Colors.blue, // Warna teks yang diinginkan
                      fontSize: 18,
                    ),
                  ),
                ),
                child: Transform.scale(
                  scaleX: 1.5,
                  scaleY: 1.1,
                  child: Container(
                    height: 216,
                    width: MediaQuery.of(context)
                        .size
                        .width, // Memastikan mengambil seluruh lebar layar
                    child: CupertinoDatePicker(
                      // initialDateTime: initialDateTime,
                      initialDateTime: initialDateTime,
                      minimumDate: isStartDate ? initialDateTime : minimumDate,
                      itemExtent: 40,
                      mode: CupertinoDatePickerMode.date,
                      onDateTimeChanged: (DateTime newDateTime) {
                        selectedDateTime = newDateTime;
                      },
                    ),
                  ),
                ),
              ),
              Divider(),
              Container(
                width: MediaQuery.sizeOf(context).width - 30,
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue,
                      foregroundColor: Colors.white,
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(20))),
                  onPressed: () {
                    if (isStartDate) {
                      context
                          .read<DatePickBloc>()
                          .add(PickStartDateEvent(selectedDateTime));
                    } else {
                      context
                          .read<DatePickBloc>()
                          .add(PickEndDateEvent(selectedDateTime));
                    }
                    Navigator.pop(context);
                  },
                  child: const Text("Terapkan"),
                ),
              )
            ],
          )),
        );
      },
    );
  }
  void custom(
      BuildContext context, bool isStartDate, DateTime initialDateTime,{
        DateTime? initialDateTimeEnd
      }) {
    final currentState = BlocProvider.of<DatePickBloc>(context).state;
    DateTime? minimumDate;
    DateTime? minimumDateIsStart;
    DateTime? position;
    // print(initialDateTime);
    // print(initialDateTimeEnd);
    // print(DateTime.now());

    minimumDateIsStart = initialDateTime;
    if (currentState is DateSelected) {
      if (isStartDate) {
          position = currentState.startDate ?? initialDateTime;
        // if (initialDateTime.month != DateTime.now().month) {
        //   position = initialDateTime;
        // } else {
        //   position = currentState.startDate;
        // }
      } else {
        minimumDate = currentState.startDate;
        if (initialDateTime.month != DateTime.now().month) {
          initialDateTime = currentState.startDate;
          position = DateTime.now();
        } else {
          initialDateTime = currentState.startDate.isAfter(DateTime.now())
              ? currentState.startDate
              : DateTime.now();
          position = DateTime.now();
        }
      }
    }

    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      isScrollControlled: true,
      builder: (context) {
        DateTime selectedDateTime = initialDateTime; // Use initialDateTime here
        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,
                      // selectedDate: isStartDate &&
                      //         initialDateTime.month != DateTime.now().month
                      //     ? initialDateTime
                      //     : (isStartDate ? position : initialDateTimeEnd ?? initialDateTime),
                      selectedDate: isStartDate
                          ? position
                          : (isStartDate ? position : initialDateTimeEnd ?? initialDateTime),
                      bahasa: snapshot.data,
                      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) {
                          context
                              .read<DatePickBloc>()
                              .add(PickStartDateEvent(selectedDateTime));
                        } else {
                          context
                              .read<DatePickBloc>()
                              .add(PickEndDateEvent(selectedDateTime));
                        }
                        Navigator.pop(context);
                      },
                    ),
                  )
                ],
              ));
            } else {
              return Container();
            }
          },
        );
      },
    );
  }

}
