import 'package:absenkuv3/Bloc/Aktivitas/AbsensiAktivitasBloc.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/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/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 HalamanPengajuanAktivitasForm extends StatefulWidget {
  @override
  _HalamanPengajuanAktivitasFormState createState() =>
      _HalamanPengajuanAktivitasFormState();
}

class _HalamanPengajuanAktivitasFormState
    extends State<HalamanPengajuanAktivitasForm> {
  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();
  List<MultiImagePickerModel>? listImage;
  TimeOfDay? jam;
  DataLokasi? lokasi;
  TextEditingController jamRaw = new TextEditingController();
  final dateFormatView = DateFormat('d MMMM yyyy', 'id_ID');

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

  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<PageAktivitasModel>(
          future: PengaturanBahasa().aktivitas(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return Scaffold(
                key: scaffoldKey,
                resizeToAvoidBottomInset: true,
                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: Column(
                  children: [
                    Expanded(
                      child: SingleChildScrollView(
                        padding: EdgeInsets.fromLTRB(20, 24, 14, 18),
                        child: Form(
                          key: formKey,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              BlocListener<MultiImagePickerBloc,
                                  MultiImagePickerState>(
                                listener: (BuildContext context,
                                    MultiImagePickerState state) {
                                  if (state is MultiImageSuccessState)
                                    listImage = state.listData;
                                },
                                child: TemplateMultiImagePickerAktivitas(
                                  multiImage: false,
                                  fromCamera: false,
                                  defaultCamera: 'back',
                                ),
                              ),
                              SizedBox(
                                height: 12,
                              ),
                              BlocListener<TemplateTimePickerBloc, TimeOfDay>(
                                listener:
                                    (BuildContext context, TimeOfDay time) {
                                  // ignore: unnecessary_null_comparison
                                  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',
                                  marginHorizontal: 5,
                                ),
                              ),
                              TemplateTextFormV2(
                                adaValidasi: true,
                                controller: keterangan,
                                color: Colors.black,
                                maxLine: 5,
                                fontSize: 14,
                                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 (listImage == null ||
                              listImage!.length == 0) {
                            showSnackBarDelayed(scaffoldKey,
                                'Gambar tidak boleh kosong', context);
                          } else {
                            if (formKey.currentState!.validate()) {
                              // BlocProvider.of<NavigatorBloc>(context)
                              //     .add(NavigatePop(context));
                              BlocProvider.of<AbsensiAktivitasBloc>(context)
                                  .add(TambahAbsenAktivitasEvent(
                                      context,
                                      scaffoldKey,
                                      DataAbsensi(
                                        lokasiAbsen: lokasi!.namaKantor,
                                        latitude: lokasi!.latAsli,
                                        longitude: lokasi!.longAsli,
                                        keteranganAbsen: keterangan.text,
                                        foto: listImage![0].base64,
                                        tanggal: tanggal.text,
                                        jam: jamRaw.text,
                                        jenisKamera: 'galeri',
                                      )));
                            }
                          }
                        },
                        radius: CustomStyle.formRadius + 6,
                        label:
                            "${snapshot.data!.menuAktivitas!.button!.btnSubmit}",
                        color: CustomStyle.color1,
                        expand: true,
                        bold: true,
                        heightButton: 40,
                      ),
                    ),
                  ],
                ),
              );
            } else {
              return CircularProgressIndicator(strokeWidth: 8);
            }
          }),
    );
  }
}
