import 'package:absenkuv3/Bloc/CustomFunction.dart';
import 'package:absenkuv3/Bloc/Dropdown/DropdownJenisIzinBloc.dart';
import 'package:absenkuv3/Bloc/Izin/IzinBloc.dart';
import 'package:absenkuv3/Bloc/Izin/JumlahIzinBloc.dart';
import 'package:absenkuv3/Bloc/Izin/SisaCutiBloc.dart';
import 'package:absenkuv3/Repository/Model/PageModel/mIzinPage.dart';
import 'package:absenkuv3/Repository/Model/mIzin.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Modul/Izin/KomponenIzin.dart';
import 'package:absenkuv3/UI/Template/BottomSheet/BottomSheetJenisIzin.dart';
import 'package:absenkuv3/UI/Template/CupertinoPicker/Bloc/date_pick_bloc.dart';
import 'package:absenkuv3/UI/Template/CupertinoPicker/UI/DatePickCupertinoRange.dart';
import 'package:absenkuv3/UI/Template/DateRangePicker/Bloc/DateRangePickerBloc.dart';
import 'package:absenkuv3/UI/Template/MultiImagePicker/Bloc/MultiImagePickerBloc.dart';
import 'package:absenkuv3/UI/Template/MultiImagePicker/Model/MultiImagePickerModel.dart';
import 'package:absenkuv3/UI/Template/MultiImagePicker/UI/templateMultiImagePickerV2.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:absenkuv3/UI/Template/templateButton.dart';
import 'package:absenkuv3/UI/Template/templateTextFormV2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:shimmer/shimmer.dart';

class HalamanPengajuanIzin extends StatefulWidget {
  @override
  _HalamanPengajuanIzinState createState() => _HalamanPengajuanIzinState();
}

class _HalamanPengajuanIzinState extends State<HalamanPengajuanIzin> {
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final dateFormat = new DateFormat('yyyy-MM-dd');
  String? tanggalMulai;
  String? tanggalSelesai;
  String? sisaCuti;
  DataJenisIzin? dataJenisIzin;
  int? backDate = 0;
  String? flagKalender = '0';
  TextEditingController keterangan = new TextEditingController();
  TextEditingController jumlahIzin = new TextEditingController();
  List<MultiImagePickerModel>? listImage;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    BlocProvider.of<DateRangePickerBloc>(context).add(InitialDate());
    BlocProvider.of<DatePickBloc>(context).add(ClearDatesEvent());

    BlocProvider.of<SisaCutiBloc>(context).add(GetSisaCuti());
  }

  Future<bool> keluar() async {
    BlocProvider.of<DateRangePickerBloc>(context).add(InitialDate());
    Navigator.pop(context);
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: keluar,
      child: FutureBuilder<PageIzinModel>(
          future: PengaturanBahasa().izin(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return Scaffold(
                key: scaffoldKey,
                backgroundColor: Colors.white,
                appBar: AppBar(
                  centerTitle: true,
                  title: Text(
                    snapshot.data!.menuIzin!.title!.parentTitle!,
                    style: TextStyle(fontSize: CustomStyle.fontSizeTitle),
                  ),
                  flexibleSpace: Image(
                    image: AssetImage(ValueImage.headerBiruDashboard),
                    fit: BoxFit.cover,
                  ),
                  backgroundColor: Colors.transparent,
                ),
                body: Column(
                  children: [
                    Expanded(
                      child: SingleChildScrollView(
                        padding: EdgeInsets.fromLTRB(14, 24, 14, 18),
                        child: Form(
                          key: formKey,
                          child: Column(
                            children: [
                              BlocListener<DropdownJenisIzinBloc,
                                  DropdownState>(
                                listener: (BuildContext context,
                                    DropdownState state) {
                                  if (state is DropdownSuccessState &&
                                      state.selectedValue != null) {
                                    dataJenisIzin = state.selectedValue;
                                    backDate = state.selectedValue!.backDate;
                                    flagKalender =
                                        state.selectedValue!.flagKalender;
                                    BlocProvider.of<DatePickBloc>(context)
                                        .add(ClearDatesEvent());
                                    BlocProvider.of<JumlahIzinBloc>(context)
                                        .add(Hidden());
                                  }
                                },
                                child: BottomSheetJenisizin(
                                  snapshot.data!.menuIzin!.data!.jenisIzin!
                                  // color: Colors.grey[600],
                                  // marginHorizontal: 13,
                                ),
                              ),
                              BlocBuilder<DropdownJenisIzinBloc, DropdownState>(
                                  builder: (BuildContext context,
                                      DropdownState state) {
                                if (state is DropdownSuccessState &&
                                    state.selectedValue != null)
                                  return InformasiIzin(
                                      state.selectedValue!.informasi!,
                                      snapshot.data!.menuIzin!);
                                else
                                  return Container();
                              }),
                              Container(
                                margin: EdgeInsets.only(bottom: 12),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    BlocBuilder<DropdownJenisIzinBloc,
                                            DropdownState>(
                                        builder: (BuildContext context,
                                            DropdownState state) {
                                      if (state is DropdownSuccessState &&
                                          state.selectedValue != null) {
                                        backDate =
                                            state.selectedValue!.backDate;
                                      }
                                      return BlocListener<DatePickBloc,
                                              DatePickState>(
                                          listener: (context, state) {
                                            if (state is DateSelected) {
                                              if (state.endDate != null) {
                                                tanggalMulai = dateFormat
                                                    .format(state.startDate);
                                                tanggalSelesai = dateFormat
                                                    .format(state.endDate!);
                                                BlocProvider.of<JumlahIzinBloc>(
                                                        context)
                                                    .add(GetJumlahIzin(
                                                        tanggalMulai,
                                                        tanggalSelesai,
                                                        flagKalender));
                                              }
                                            }
                                          },
                                          child: DatePickCupertinoRange(
                                            firstDate: DateTime.now().subtract(
                                                Duration(days: backDate!)),
                                            // firstDate: DateTime(
                                            //     DateTime.now().year,
                                            //     DateTime.now().month,
                                            //     DateTime.now().day).subtract(Duration(days: backDate!)),
                                          ));
                                    })
                                  ],
                                ),
                              ),
                              BlocBuilder<JumlahIzinBloc, JumlahIzinState>(
                                builder: (BuildContext context,
                                    JumlahIzinState state) {
                                  if (state is JumlahIzinSuccess) {
                                    jumlahIzin.text =
                                        state.basicSimpleRespon.data!;
                                    return Container(
                                      padding: EdgeInsets.symmetric(
                                          vertical: 15, horizontal: 10),
                                      margin: EdgeInsets.only(bottom: 10),
                                      decoration: BoxDecoration(
                                          borderRadius:
                                              BorderRadius.circular(10),
                                          color: Color(0XFFF1F3FA)),
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(
                                              '${snapshot.data!.menuIzin!.data!.jumlahIzin}'),
                                          Text(
                                              '${state.basicSimpleRespon.data!} ${snapshot.data!.menuIzin!.data!.hari}'),
                                        ],
                                      ),
                                    );
                                  } else if (state is JumlahIzinProgress)
                                    return Container(
                                      height: CustomStyle.formHeight,
                                      width: MediaQuery.of(context).size.width,
                                      child: Shimmer.fromColors(
                                        baseColor: Colors.grey[200]!,
                                        highlightColor: Colors.white,
                                        period: Duration(seconds: 4),
                                        child: Card(),
                                      ),
                                    );
                                  else
                                    return Container();
                                },
                              ),
                              BlocBuilder<DropdownJenisIzinBloc, DropdownState>(
                                  builder: (BuildContext context,
                                      DropdownState state) {
                                if (state is DropdownSuccessState &&
                                    state.selectedValue != null &&
                                    state.selectedValue!.flag == '1')
                                  return BlocBuilder<SisaCutiBloc,
                                      SisaCutiState>(
                                    builder: (BuildContext context,
                                        SisaCutiState state) {
                                      sisaCuti = state.basicSimpleRespon != null
                                          ? state.basicSimpleRespon!.data
                                              .toString()
                                          : '0';
                                      return Container(
                                        padding: EdgeInsets.symmetric(
                                            vertical: 15, horizontal: 10),
                                        margin: EdgeInsets.only(bottom: 15),
                                        decoration: BoxDecoration(
                                            borderRadius:
                                                BorderRadius.circular(10),
                                            color: Color(0XFFF1F3FA)),
                                        child: Row(
                                          mainAxisAlignment:
                                              MainAxisAlignment.spaceBetween,
                                          children: [
                                            Text(
                                                '${snapshot.data!.menuIzin!.data!.infoSisaCuti}'),
                                            Text(
                                                '${sisaCuti} ${snapshot.data!.menuIzin!.data!.hari}'),
                                          ],
                                        ),
                                      );
                                    },
                                  );
                                else
                                  return Container();
                              }),
                              TemplateTextFormV2(
                                adaValidasi: true,
                                controller: keterangan,
                                color: Colors.black,
                                maxLine: 5,
                                fontSize: 13,
                                titleText:
                                    '${snapshot.data!.menuIzin!.data!.keterangan}',
                                radius: CustomStyle.formRadius,
                                // hintText: "Email",
                              ),
                              SizedBox(
                                height: 12,
                              ),
                              BlocListener<MultiImagePickerBloc,
                                  MultiImagePickerState>(
                                listener: (BuildContext context,
                                    MultiImagePickerState state) {
                                  if (state is MultiImageSuccessState)
                                    listImage = state.listData;
                                },
                                child: TemplateMultiImagePickerV2(
                                  fromCamera: true,
                                  defaultCamera: 'back',
                                  maxUpload: 2,
                                ),
                              ),
                              SizedBox(
                                height: 12,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                    Container(
                      color: Colors
                          .white, // Optional: add background color to the button
                      padding: EdgeInsets.all(14), // Padding around the button
                      child: TemplateButton(
                        onClick: () {
                          if (dataJenisIzin == null) {
                            showSnackBarDelayed(
                                scaffoldKey,
                                '${snapshot.data!.menuIzin!.pesanKonfirmasi!.jenisIsEmpty}',
                                context);
                          } else if (tanggalMulai == null ||
                              tanggalSelesai == null) {
                            showSnackBarDelayed(
                                scaffoldKey,
                                '${snapshot.data!.menuIzin!.pesanKonfirmasi!.tanggalIsEmpty}',
                                context);
                          } else if (keterangan.text.isEmpty) {
                            showSnackBarDelayed(
                                scaffoldKey,
                                '${snapshot.data!.menuIzin!.pesanKonfirmasi!.ketIsEmpty}',
                                context);
                          } else if ((listImage == null ||
                                  listImage!.length == 0) &&
                              dataJenisIzin!.flagFile == '1') {
                            showSnackBarDelayed(
                                scaffoldKey,
                                '${snapshot.data!.menuIzin!.pesanKonfirmasi!.fileIsEmpty}',
                                context);
                          } else {
                            BlocProvider.of<IzinBloc>(context).add(
                                pengajuanIzin(
                                    ModelIzin(
                                        dataJenisIzin!.id,
                                        dataJenisIzin!.nama,
                                        dataJenisIzin!.jenisIzin,
                                        tanggalMulai,
                                        tanggalSelesai,
                                        keterangan.text,
                                        listImage,
                                        jumlahIzin.text,
                                        sisaCuti: sisaCuti,
                                        flag: dataJenisIzin!.flag),
                                    context,
                                    scaffoldKey,
                                    formKey));
                          }
                        },
                        radius: CustomStyle.formRadius + 6,
                        label: "${snapshot.data!.menuIzin!.button!.btnSubmit}",
                        color: CustomStyle.color1,
                        expand: true,
                        bold: true,
                        heightButton: 40,
                      ),
                    ),
                  ],
                ),
              );
            } else {
              return CircularProgressIndicator(strokeWidth: 8);
            }
          }),
    );
  }
}
