import 'package:absenkuv3/Bloc/AuthBloc.dart';
import 'package:absenkuv3/Bloc/CustomFunction.dart';
import 'package:absenkuv3/Bloc/Dropdown/DropdownJenisReimbursementBloc.dart';
import 'package:absenkuv3/Bloc/Reimbursement/ReimbursementItemBloc.dart';
import 'package:absenkuv3/Repository/Model/PageModel/mReimbursementPage.dart';
import 'package:absenkuv3/Repository/Model/mDropdown.dart';
import 'package:absenkuv3/Repository/Model/mLogin.dart';
import 'package:absenkuv3/Repository/Model/mReimbursement.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Modul/Dropdown/DropdownJenisReimbursement.dart';
import 'package:absenkuv3/UI/Template/DatePicker/Bloc/DatePickerMulaiBloc.dart';
import 'package:absenkuv3/UI/Template/DatePicker/UI/templateDatePicker.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/style.dart';
import 'package:absenkuv3/UI/Template/templateButton.dart';
import 'package:absenkuv3/UI/Template/templateForm.dart';
import 'package:absenkuv3/UI/Template/templateTextFieldForm.dart';
import 'package:extended_masked_text/extended_masked_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';

class HalamanTambahItemPengajuanReimbursement extends StatefulWidget {
  final DataItem? dataItem;
  HalamanTambahItemPengajuanReimbursement(this.dataItem);
  @override
  _HalamanTambahItemPengajuanReimbursementState createState() =>
      _HalamanTambahItemPengajuanReimbursementState();
}

class _HalamanTambahItemPengajuanReimbursementState
    extends State<HalamanTambahItemPengajuanReimbursement> {
  final dateFormat = new DateFormat('yyyy-MM-dd');
  TextEditingController keterangan = new TextEditingController();
  TextEditingController nominal = MoneyMaskedTextController(
      thousandSeparator: '.',
      leftSymbol: 'Rp ',
      precision: 0,
      decimalSeparator: '');
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  DataDropdown? dataJenis;
  List<MultiImagePickerModel>? listImage;
  String? tglNota;
  String title = 'Tambah';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<PageReimbursementModel>(
        future: PengaturanBahasa().reimbursement(),
        builder: (context, snapshot){
          if(snapshot.connectionState == ConnectionState.done){
            snapshot.data!.menuReimbursement!.locale == 'id'
              ? title = 'Tambah'
              : title = 'Add';
            if (widget.dataItem != null) {
              //REVISI REIMBURSEMENT
              title = snapshot.data!.menuReimbursement!.button!.btnRevisi!;
              nominal.text = widget.dataItem!.nominal.toString();
              keterangan.text = widget.dataItem!.keterangan!;
            }
            return Scaffold(
              key: scaffoldKey,
              backgroundColor: Colors.white,
              appBar: AppBar(
                flexibleSpace: Image(
                  image: AssetImage(ValueImage.headerBiruDashboard),
                  fit: BoxFit.cover,
                ),
                backgroundColor: Colors.transparent,
                centerTitle: true,
                title: Text(
                  '$title ${snapshot.data!.menuReimbursement!.title}',
                  style: TextStyle(fontSize: CustomStyle.fontSizeTitle),
                ),
              ),
              body: BlocBuilder<AuthBloc, LoginRespon>(
                builder: (BuildContext context, LoginRespon loginRespon) {
                  return SingleChildScrollView(
                    child: Container(
                      padding: EdgeInsets.fromLTRB(14, 24, 14, 18),
                      child: Form(
                        key: formKey,
                        child: Column(
                          children: [
                            BlocListener<DropdownJenisReimbursementBloc, DropdownState>(
                              listener: (BuildContext context, DropdownState state) {
                                if (state is DropdownSuccessState &&
                                    state.selectedValue != null) {
                                  dataJenis = state.selectedValue;
                                }
                              },
                              child: DropdownJenisReimbursement(
                                initialData: widget.dataItem != null
                                    ? widget.dataItem!.jenis ?? null
                                    : null,
                                color: Colors.grey[600],
                              ),
                            ),
                            TemplateForm(
                              controller: nominal,
                              titleText: snapshot.data!.menuReimbursement!.data!.nominal,
                              color: Colors.grey[600],
                              radius: 6,
                              hintText: snapshot.data!.menuReimbursement!.data!.nominal,
                              keyboardNumber: true,
                              numberOnly: true,
                              formHeight: CustomStyle.formHeight,
                            ),
                            SizedBox(
                              height: 8,
                            ),
                            Container(
                              margin: EdgeInsets.only(bottom: 12),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.only(bottom: 8),
                                    child: Text(
                                      snapshot.data!.menuReimbursement!.data!.tanggalNote!,
                                      style: TextStyle(
                                          color: Colors.grey[600],
                                          fontWeight: FontWeight.bold,
                                          fontSize: 14),
                                    ),
                                  ),
                                  BlocListener<DatePickerMulaiBloc, DateTime>(
                                    listener: (BuildContext context, DateTime date) {
                                      tglNota = dateFormat.format(date);
                                    },
                                    child: TemplateDatePicker(
                                      snapshot.data!.menuReimbursement!.data!.tanggalNote!,
                                      initialData: widget.dataItem != null
                                          ? widget.dataItem!.tglNotaRaw ?? null
                                          : null,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            TemplateTextFieldForm(
                              adaValidasi: true,
                              controller: keterangan,
                              color: Colors.grey[600],
                              maxLine: 3,
                              minLine: 3,
                              titleText: snapshot.data!.menuReimbursement!.data!.keterangan,
                              radius: CustomStyle.formRadius,
                              hintText: snapshot.data!.menuReimbursement!.data!.keterangan,
                            ),
                            BlocListener<MultiImagePickerBloc, MultiImagePickerState>(
                              listener:
                                  (BuildContext context, MultiImagePickerState state) {
                                if (state is MultiImageSuccessState)
                                  listImage = state.listData;
                              },
                              child: TemplateMultiImagePicker(
                                initialData: widget.dataItem != null &&
                                    widget.dataItem!.file != '-' &&
                                    widget.dataItem!.file != null
                                    ? [widget.dataItem!.file]
                                    : null,
                                fromCamera: true,
                                multiImage: false,
                                defaultCamera: 'back',
                                pluginCamera: loginRespon.dataLogin!.kamera,
                              ),
                            ),
                            SizedBox(
                              height: 12,
                            ),
                            TemplateButton(
                              onClick: () {
                                if (widget.dataItem == null) {
                                  if (listImage == null || listImage!.length == 0)
                                    showSnackBarDelayed(
                                        scaffoldKey, snapshot.data!.menuReimbursement!.message!.emptyFoto, context);
                                  else {
                                    BlocProvider.of<ReimbursementItemBloc>(context).add(
                                        TambahReimbursementItemEvent(
                                            context,
                                            scaffoldKey,
                                            formKey,
                                            ListItemTemp(
                                                idJenisPlafon: dataJenis!.id,
                                                nominal: int.parse(nominal.text
                                                    .replaceAll(RegExp('[^0-9]'), '')),
                                                tglBukti: tglNota,
                                                keterangan: keterangan.text,
                                                file: listImage![0].base64)));
                                  }
                                } else {
                                  //REVISI
                                  Navigator.pop(
                                      context,
                                      DataItem(
                                          idItem: widget.dataItem!.idItem,
                                          idJenis: dataJenis != null
                                              ? dataJenis!.id
                                              : widget.dataItem!.idJenis,
                                          nominal: int.parse(nominal.text
                                              .replaceAll(RegExp('[^0-9]'), '')),
                                          tglNota: tglNota,
                                          keterangan: keterangan.text,
                                          file: listImage != null
                                              ? listImage![0].base64
                                              : null,
                                          editedPhotoPath: listImage != null
                                              ? listImage![0].path
                                              : null));
                                }
                              },
                              radius: CustomStyle.formRadius + 6,
                              label: title,
                              color: CustomStyle.color1,
                              expand: true,
                              bold: true,
                              heightButton: 40,
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            );
          }else{
            return CircularProgressIndicator(strokeWidth: 8);
          }
        }
    );
  }
}

class HalamanEditItemPengajuanReimbursement extends StatefulWidget {
  final ListItemTemp? dataItem;
  HalamanEditItemPengajuanReimbursement(this.dataItem);
  @override
  _HalamanEditItemPengajuanReimbursementState createState() =>
      _HalamanEditItemPengajuanReimbursementState();
}

class _HalamanEditItemPengajuanReimbursementState
    extends State<HalamanEditItemPengajuanReimbursement> {
  final dateFormat = new DateFormat('yyyy-MM-dd');
  TextEditingController keterangan = new TextEditingController();
  TextEditingController nominal = MoneyMaskedTextController(
      thousandSeparator: '.',
      leftSymbol: 'Rp ',
      precision: 0,
      decimalSeparator: '');
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  DataDropdown? dataJenis;
  List<MultiImagePickerModel>? listImage;
  String? tglNota;
  String title = 'Edit';

  @override
  void initState() {
    if (widget.dataItem != null) {
      //REVISI REIMBURSEMENT
      // title = 'Revisi';
      nominal.text = widget.dataItem!.nominal.toString();
      keterangan.text = widget.dataItem!.keterangan!;
    }
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<PageReimbursementModel>(
        future: PengaturanBahasa().reimbursement(),
        builder: (context, snapshot){
          if(snapshot.connectionState == ConnectionState.done){
            return Scaffold(
              key: scaffoldKey,
              backgroundColor: Colors.white,
              appBar: AppBar(
                flexibleSpace: Image(
                  image: AssetImage(ValueImage.headerBiruDashboard),
                  fit: BoxFit.cover,
                ),
                backgroundColor: Colors.transparent,
                centerTitle: true,
                title: Text(
                  '$title ${snapshot.data!.menuReimbursement!.title}',
                  style: TextStyle(fontSize: CustomStyle.fontSizeTitle),
                ),
              ),
              body: BlocBuilder<AuthBloc, LoginRespon>(
                builder: (BuildContext context, LoginRespon loginRespon) {
                  return SingleChildScrollView(
                    child: Container(
                      padding: EdgeInsets.fromLTRB(14, 24, 14, 18),
                      child: Form(
                        key: formKey,
                        child: Column(
                          children: [
                            BlocListener<DropdownJenisReimbursementBloc, DropdownState>(
                              listener: (BuildContext context, DropdownState state) {
                                if (state is DropdownSuccessState &&
                                    state.selectedValue != null) {
                                  dataJenis = state.selectedValue;
                                }
                              },
                              child: DropdownJenisReimbursement(
                                initialData: widget.dataItem != null
                                    ? widget.dataItem!.jenisPlafon ?? null
                                    : null,
                                color: Colors.grey[600],
                              ),
                            ),
                            TemplateForm(
                              controller: nominal,
                              titleText: snapshot.data!.menuReimbursement!.data!.nominal,
                              color: Colors.grey[600],
                              radius: 6,
                              hintText: snapshot.data!.menuReimbursement!.data!.nominal,
                              keyboardNumber: true,
                              numberOnly: true,
                              formHeight: CustomStyle.formHeight,
                            ),
                            SizedBox(
                              height: 8,
                            ),
                            Container(
                              margin: EdgeInsets.only(bottom: 12),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.only(bottom: 8),
                                    child: Text(
                                      snapshot.data!.menuReimbursement!.data!.tanggalNote!,
                                      style: TextStyle(
                                          color: Colors.grey[600],
                                          fontWeight: FontWeight.bold,
                                          fontSize: 14),
                                    ),
                                  ),
                                  BlocListener<DatePickerMulaiBloc, DateTime>(
                                    listener: (BuildContext context, DateTime date) {
                                      tglNota = dateFormat.format(date);
                                    },
                                    child: TemplateDatePicker(
                                      'Tanggal Nota',
                                      initialData: widget.dataItem != null
                                          ? widget.dataItem!.tglBuktiRaw ?? null
                                          : null,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            TemplateTextFieldForm(
                              adaValidasi: true,
                              controller: keterangan,
                              color: Colors.grey[600],
                              maxLine: 3,
                              minLine: 3,
                              titleText: snapshot.data!.menuReimbursement!.data!.keterangan,
                              radius: CustomStyle.formRadius,
                              hintText: snapshot.data!.menuReimbursement!.data!.keterangan,
                            ),
                            BlocListener<MultiImagePickerBloc, MultiImagePickerState>(
                              listener:
                                  (BuildContext context, MultiImagePickerState state) {
                                if (state is MultiImageSuccessState)
                                  listImage = state.listData;
                              },
                              child: TemplateMultiImagePicker(
                                initialData: widget.dataItem != null &&
                                    widget.dataItem!.file != '-' &&
                                    widget.dataItem!.file != null
                                    ? [widget.dataItem!.file]
                                    : null,
                                fromCamera: true,
                                multiImage: false,
                                defaultCamera: 'back',
                                pluginCamera: loginRespon.dataLogin!.kamera,
                              ),
                            ),
                            SizedBox(
                              height: 12,
                            ),
                            TemplateButton(
                              onClick: () {
                                BlocProvider.of<ReimbursementItemBloc>(context).add(
                                    EditReimbursementItemEvent(
                                        context,
                                        scaffoldKey,
                                        formKey,
                                        ListItemTemp(
                                            id: widget.dataItem!.id,
                                            idJenisPlafon: dataJenis == null
                                                ? widget.dataItem!.idJenisPlafon
                                                : dataJenis!.id,
                                            nominal: int.parse(nominal.text
                                                .replaceAll(RegExp('[^0-9]'), '')),
                                            tglBukti: tglNota,
                                            keterangan: keterangan.text,
                                            file: listImage == null
                                                ? null
                                                : listImage![0].base64)));
                              },
                              radius: CustomStyle.formRadius + 6,
                              label: title,
                              color: CustomStyle.color1,
                              expand: true,
                              bold: true,
                              heightButton: 40,
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
            );
          }else{
            return CircularProgressIndicator(strokeWidth: 8);
          }
        }
    );
  }
}
