import 'package:absenkuv3/Bloc/Aktivitas/AbsensiAktivitasBloc.dart';
import 'package:absenkuv3/Bloc/Aktivitas/EditAktivitasBloc.dart';
import 'package:absenkuv3/Bloc/CustomFunction.dart';
import 'package:absenkuv3/Bloc/Dropdown/DropdownLokasiAktivitasBloc.dart';
import 'package:absenkuv3/Repository/Model/PageModel/mAktivitasPage.dart';
import 'package:absenkuv3/Repository/Model/mDropdownLokasi.dart';
import 'package:absenkuv3/Repository/Model/mLembur.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Template/BottomSheet/BottomSheetLokasiKantor.dart';
import 'package:absenkuv3/UI/Template/CupertinoPicker/Bloc/date_pick_bloc.dart';
import 'package:absenkuv3/UI/Template/DatePicker/Bloc/DatePickerTglLahirBloc.dart';
import 'package:absenkuv3/UI/Template/DatePicker/Bloc/TemplateTimePickerBloc.dart';
import 'package:absenkuv3/UI/Template/DatePicker/UI/templateDatePickerTanggalAktivitas.dart';
import 'package:absenkuv3/UI/Template/DatePicker/UI/templateTimePickerAktivitas.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/templateMultiImagePicker.dart';
import 'package:absenkuv3/UI/Template/MultiImagePicker/UI/templateMultiImagePickerAktivitas.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_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';

class HalamanEditAktivitasForm extends StatefulWidget {
  var data;
  HalamanEditAktivitasForm({Key? key, this.data}) : super(key: key);
  @override
  _HalamanEditAktivitasFormState createState() =>
      _HalamanEditAktivitasFormState();
}

class _HalamanEditAktivitasFormState extends State<HalamanEditAktivitasForm> {
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final dateFormat = new DateFormat('yyyy-MM-dd');
  TextEditingController tanggal = new TextEditingController(text: '0000-00-00');
  TextEditingController tanggalRaw = new TextEditingController();
  TextEditingController keterangan = new TextEditingController();
  TimeOfDay? jam;
  DataLokasi? lokasi;
  TextEditingController jamRaw = new TextEditingController();
  final dateFormatView = DateFormat('d MMMM yyyy', 'id_ID');
  List<MultiImagePickerModel>? listImageFile;

  @override
  void initState() {
    super.initState();
    BlocProvider.of<EditAktivitasBloc>(context)
        .add(GetEditAktivitas(widget.data[0]));
    BlocProvider.of<DatePickBloc>(context).add(ClearDatesEvent());
  }

  Future<bool> keluar() async {
    Navigator.pop(context);
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: keluar,
      child: FutureBuilder<PageAktivitasModel>(
          future: PengaturanBahasa().aktivitas(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return Scaffold(
                key: scaffoldKey,
                backgroundColor: Colors.white,
                appBar: AppBar(
                  centerTitle: true,
                  title: Text(
                    snapshot.data!.menuAktivitas!.title!,
                    style: TextStyle(fontSize: CustomStyle.fontSizeTitle),
                  ),
                  flexibleSpace: Image(
                    image: AssetImage(ValueImage.headerBiruDashboard),
                    fit: BoxFit.cover,
                  ),
                  backgroundColor: Colors.transparent,
                ),
                body: BlocBuilder<EditAktivitasBloc, EditAktivitasState>(
                    builder: (context, state) {
                  if (state is EditAktivitasProgress) {
                    return Center(
                      child: CircularProgressIndicator(strokeWidth: 8),
                    );
                  } else if (state is EditAktivitasError) {
                    return Center(
                        child: Image.asset(
                      ValueImage.noData,
                      height: 250,
                    ));
                  } else if (state is EditAktivitasSuccess) {
                    final aktivitas = state.aktivitasRespon.data![0];
                    tanggal.text = aktivitas.tglAktivitas ?? '0000-00-00';
                    BlocProvider.of<DatePickerTglLahirBloc>(context).add(
                        SetDate(DateTime(
                            int.parse(aktivitas.tglAktivitas!.split('-')[0]),
                            int.parse(aktivitas.tglAktivitas!.split('-')[1]),
                            int.parse(aktivitas.tglAktivitas!.split('-')[2]))));
                    tanggalRaw.text = dateFormatView.format(DateTime(
                        int.parse(aktivitas.tglAktivitas!.split('-')[0]),
                        int.parse(aktivitas.tglAktivitas!.split('-')[1]),
                        int.parse(aktivitas.tglAktivitas!.split('-')[2])));
                    jamRaw.text = aktivitas.waktuAktivitas ?? '';
                    jam = aktivitas.waktuAktivitas != null
                        ? TimeOfDay(
                            hour: int.parse(
                                aktivitas.waktuAktivitas!.split(':')[0]),
                            minute: int.parse(
                                aktivitas.waktuAktivitas!.split(':')[1]),
                          )
                        : null;
                    BlocProvider.of<TemplateTimePickerBloc>(context)
                        .add(SetTime(jam!));
                    keterangan.text = aktivitas.keterangan ?? '';
                    lokasi = DataLokasi(
                      namaKantor: aktivitas.lokasi,
                      latAsli: aktivitas.latitude,
                      longAsli: aktivitas.longitude,
                    );
                    BlocProvider.of<DropdownLokasiAktivitasBloc>(context)
                        .add(SelectDataDropdown(lokasi));
                    return Column(
                      children: [
                        Expanded(
                          child: SingleChildScrollView(
                            padding: EdgeInsets.fromLTRB(20, 24, 14, 18),
                            child: Form(
                              key: formKey,
                              child: Column(
                                children: [
                                  BlocListener<MultiImagePickerBloc,
                                      MultiImagePickerState>(
                                    listener: (BuildContext context,
                                        MultiImagePickerState st) {
                                      if (st is MultiImageSuccessState) {
                                        if (st.listData.length == 0) {
                                          if (state.aktivitasRespon.data![0]
                                                  .image !=
                                              null)
                                            state.aktivitasRespon.data![0]
                                                .image = "";
                                          listImageFile = null;
                                        } else {
                                          listImageFile = st.listData;
                                        }
                                      }
                                    },
                                    child: TemplateMultiImagePickerAktivitas(
                                      multiImage: false,
                                      fromCamera: false,
                                      initialData: state.aktivitasRespon
                                                  .data![0].image ==
                                              ""
                                          ? null
                                          : [
                                              state.aktivitasRespon.data![0]
                                                  .image!
                                            ],
                                      defaultCamera: 'back',
                                    ),
                                  ),
                                  SizedBox(
                                    height: 12,
                                  ),
                                  BlocListener<TemplateTimePickerBloc,
                                      TimeOfDay>(
                                    listener:
                                        (BuildContext context, TimeOfDay time) {
                                      if (time != null) {
                                        jam = time;
                                        jamRaw.text =
                                            "${jam!.hour}:${jam!.minute}";
                                      }
                                    },
                                    child: Container(
                                      child: TemplateTimePickerAktivitas(
                                        "Jam",
                                        validasi: true,
                                        initialData: jam,
                                        textEditingController: jamRaw,
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                    height: 12,
                                  ),
                                  BlocListener<DatePickerTglLahirBloc,
                                      DateTime>(
                                    listener:
                                        (BuildContext context, DateTime date) {
                                      tanggal.text = dateFormat.format(date);
                                      tanggalRaw.text =
                                          dateFormatView.format(date);
                                    },
                                    child: TemplateDatePickerTanggalAktivitas(
                                      'Tanggal ',
                                      marginHorizontal: 13,
                                      textEditingController: tanggalRaw,
                                      initialData: tanggal.text == '0000-00-00'
                                          ? null
                                          : DateTime(
                                              int.parse(
                                                  tanggal.text.split('-')[0]),
                                              int.parse(
                                                  tanggal.text.split('-')[1]),
                                              int.parse(
                                                  tanggal.text.split('-')[2])),
                                    ),
                                  ),
                                  BlocListener<DropdownLokasiAktivitasBloc,
                                      DropdownState>(
                                    listener: (BuildContext context,
                                        DropdownState state) {
                                      if (state is DropdownSuccessState &&
                                          state.selectedValue != null) {
                                        lokasi = state.selectedValue;
                                      }
                                    },
                                    child: BottomSheetLokasiKantor(
                                      'Lokasi',
                                      initialData: lokasi!.namaKantor,
                                      marginHorizontal: 5,
                                    ),
                                  ),
                                  TemplateTextFormV2(
                                    adaValidasi: true,
                                    controller: keterangan,
                                    color: Colors.black,
                                    maxLine: 5,
                                    fontSize: 13,
                                    bottomMargin: 0,
                                    titleText:
                                        '${snapshot.data!.menuAktivitas!.data!.keterangan}',
                                    radius: CustomStyle.formRadius,
                                    // hintText: "Email",
                                  ),
                                  SizedBox(
                                    height: 12,
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                        Container(
                          color: Colors.white,
                          padding: EdgeInsets.all(14),
                          child: TemplateButton(
                            onClick: () {
                              if (tanggal == null) {
                                showSnackBarDelayed(scaffoldKey,
                                    'Tanggal mulai belum dipilih', context);
                              } else if (keterangan.text.isEmpty) {
                                showSnackBarDelayed(scaffoldKey,
                                    'Keterangan tidak boleh kosong', context);
                              } else if (listImageFile == null &&
                                  state.aktivitasRespon.data![0].image == "") {
                                showSnackBarDelayed(scaffoldKey,
                                    'Gambar tidak boleh kosong', context);
                              } else {
                                if (formKey.currentState!.validate()) {
                                  // BlocProvider.of<NavigatorBloc>(context)
                                  //     .add(NavigatePop(context));
                                  BlocProvider.of<AbsensiAktivitasBloc>(context)
                                      .add(EditAbsenAktivitasEvent(
                                          context,
                                          widget.data[1],
                                          scaffoldKey,
                                          DataAbsensi(
                                            idAktivitas: widget.data[0],
                                            lokasiAbsen: lokasi!.namaKantor,
                                            latitude: lokasi!.latAsli,
                                            longitude: lokasi!.longAsli,
                                            keteranganAbsen: keterangan.text,
                                            fotoOld: state
                                                .aktivitasRespon.data![0].image,
                                            foto:
                                                listImageFile?[0]?.base64 ?? '',
                                            tanggal: tanggal.text,
                                            jam: jamRaw.text,
                                          )));
                                }
                              }
                            },
                            radius: CustomStyle.formRadius + 6,
                            label:
                                "${snapshot.data!.menuAktivitas!.button!.btnSubmit}",
                            color: CustomStyle.color1,
                            expand: true,
                            bold: true,
                            heightButton: 40,
                          ),
                        ),
                      ],
                    );
                  } else
                    return Center(
                      child: CircularProgressIndicator(strokeWidth: 8),
                    );
                }),
              );
            } else {
              return CircularProgressIndicator(strokeWidth: 8);
            }
          }),
    );
  }
}
