import 'package:absenkuv3/Bloc/CustomFunction.dart';
import 'package:absenkuv3/Bloc/Gaji/GajiBloc.dart';
import 'package:absenkuv3/Bloc/NavigatorBloc.dart';
import 'package:absenkuv3/Repository/Model/PageModel/mInfoGajiPage.dart';
import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Template/MonthPicker/Bloc/MonthPickerBloc.dart';
import 'package:absenkuv3/UI/Template/MonthPicker/UI/templateMonthPickerNonFloating.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:absenkuv3/UI/Template/templateButton.dart';
import 'package:absenkuv3/UI/Template/templateFormPassword.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class HalamanGaji extends StatefulWidget {
  @override
  _HalamanGajiState createState() => _HalamanGajiState();
}

class _HalamanGajiState extends State<HalamanGaji> {
  @override
  void initState() {
    super.initState();
    Future.delayed(Duration(milliseconds: 500), () {
      openDialog();
    });
    // BlocProvider.of<MonthPickerBloc>(context)
    //     .add(SetDate(DateTime(DateTime.now().year, DateTime.now().month - 1)));
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: keluar,
      child: FutureBuilder<PageInfoGajiModel>(
          future: PengaturanBahasa().infoGaji(),
          builder: (context, snapshot){
            if(snapshot.connectionState == ConnectionState.done){
              return Scaffold(
                backgroundColor: Colors.white,
                appBar: AppBar(
                  centerTitle: true,
                  flexibleSpace: Image(
                    image: AssetImage(ValueImage.headerBiruDashboard),
                    fit: BoxFit.cover,
                  ),
                  backgroundColor: Colors.transparent,
                  title: Text(
                    snapshot.data!.menuInfoGaji!.title!,
                    style: TextStyle(fontSize: CustomStyle.fontSizeTitle),
                  ),
                ),
                body: Stack(
                  children: [
                    BlocBuilder<GajiBloc, GajiState>(
                      builder: (BuildContext context, GajiState state) {
                        if (state is GetGajiSuccessState)
                          return Container(
                            height: MediaQuery.of(context).size.height,
                            child: SingleChildScrollView(
                              child: Column(
                                children: [
                                  SizedBox(
                                    height: 12,
                                  ),
                                  CustomExpansionTile(
                                    snapshot.data!.menuInfoGaji!.penerimaan!.header!,
                                    [
                                      TemplateRow(snapshot.data!.menuInfoGaji!.penerimaan!.gajiPokok,
                                          CurrencyFormatter.IDR(state.data!.gajiPokok)),
                                      TemplateRow(snapshot.data!.menuInfoGaji!.penerimaan!.uangMakan,
                                          CurrencyFormatter.IDR(state.data!.tMakan)),
                                      TemplateRow(snapshot.data!.menuInfoGaji!.penerimaan!.uangKomisi,
                                          CurrencyFormatter.IDR(state.data!.komisi)),
                                      TemplateRow(snapshot.data!.menuInfoGaji!.penerimaan!.uangLembur,
                                          CurrencyFormatter.IDR(state.data!.lembur)),
                                      TemplateRow(snapshot.data!.menuInfoGaji!.penerimaan!.tunjJabatan,
                                          CurrencyFormatter.IDR(state.data!.tJabatan)),
                                      TemplateRow(snapshot.data!.menuInfoGaji!.penerimaan!.tunjTransport,
                                          CurrencyFormatter.IDR(state.data!.tTransport)),
                                      TemplateRow(snapshot.data!.menuInfoGaji!.penerimaan!.tunjIstri,
                                          CurrencyFormatter.IDR(state.data!.tIstri)),
                                      TemplateRow(snapshot.data!.menuInfoGaji!.penerimaan!.tunjAnak,
                                          CurrencyFormatter.IDR(state.data!.tAnak)),
                                      TemplateRow(snapshot.data!.menuInfoGaji!.penerimaan!.penerimaanLain,
                                          CurrencyFormatter.IDR(state.data!.tLain)),
                                      TemplateRow(
                                          snapshot.data!.menuInfoGaji!.penerimaan!.ttlPenerimaan,
                                          CurrencyFormatter.IDR(
                                              state.data!.ttlPenerimaan),
                                          bold: true),
                                    ],
                                    value:
                                    CurrencyFormatter.IDR(state.data!.ttlPenerimaan),
                                  ),
                                  CustomExpansionTile(
                                      snapshot.data!.menuInfoGaji!.potongan!.header!,
                                      [
                                        TemplateRow(snapshot.data!.menuInfoGaji!.potongan!.potAbsen,
                                            CurrencyFormatter.IDR(state.data!.pAbsensi)),
                                        TemplateRow(
                                            snapshot.data!.menuInfoGaji!.potongan!.potTerlambat,
                                            CurrencyFormatter.IDR(
                                                state.data!.pKeterlambatan)),
                                        TemplateRow(snapshot.data!.menuInfoGaji!.potongan!.potKoperasi,
                                            CurrencyFormatter.IDR(state.data!.pKoperasi)),
                                        TemplateRow(
                                            snapshot.data!.menuInfoGaji!.potongan!.potBpjsKes,
                                            CurrencyFormatter.IDR(
                                                state.data!.pBpjsKesehatan)),
                                        TemplateRow(snapshot.data!.menuInfoGaji!.potongan!.potBpjsTk,
                                            CurrencyFormatter.IDR(state.data!.pBpjsTk)),
                                        TemplateRow(
                                            snapshot.data!.menuInfoGaji!.potongan!.potAsuransiKes,
                                            CurrencyFormatter.IDR(
                                                state.data!.pAsuransiKesehatan)),
                                        TemplateRow(snapshot.data!.menuInfoGaji!.potongan!.potLain,
                                            CurrencyFormatter.IDR(state.data!.pLain)),
                                        TemplateRow(
                                            snapshot.data!.menuInfoGaji!.potongan!.ttlPotongan,
                                            CurrencyFormatter.IDR(
                                                state.data!.ttlPotongan),
                                            bold: true),
                                      ],
                                      value:
                                      CurrencyFormatter.IDR(state.data!.ttlPotongan)),
                                  CustomExpansionTile(
                                    snapshot.data!.menuInfoGaji!.tunjDibiayaiPerusahaan!.header!,
                                    [
                                      TemplateRow(
                                          snapshot.data!.menuInfoGaji!.tunjDibiayaiPerusahaan!.tunjBpjsKes!,
                                          CurrencyFormatter.IDR(
                                              state.data!.tbpBpjsKesehatan)),
                                      TemplateRow(snapshot.data!.menuInfoGaji!.tunjDibiayaiPerusahaan!.tunjBpjsTk,
                                          CurrencyFormatter.IDR(state.data!.tbpBpjsTk)),
                                      TemplateRow(snapshot.data!.menuInfoGaji!.tunjDibiayaiPerusahaan!.tunjLain,
                                          CurrencyFormatter.IDR(state.data!.tbpLain)),
                                      TemplateRow(snapshot.data!.menuInfoGaji!.tunjDibiayaiPerusahaan!.ttlTunjBiayaPerusahaan,
                                          CurrencyFormatter.IDR(state.data!.ttlTbp),
                                          bold: true),
                                    ],
                                    value: CurrencyFormatter.IDR(state.data!.ttlTbp),
                                  ),
                                  TemplateContainer(snapshot.data!.menuInfoGaji!.gajiDiterima!.header,
                                      CurrencyFormatter.IDR(state.data!.gajiDiterima)),
                                  SizedBox(
                                    height: 100,
                                  ),
                                ],
                              ),
                            ),
                          );
                        else if (state is GajiErrorState)
                          return Center(
                            child: Image.asset(
                              ValueImage.noData,
                              height: 250,
                            ),
                          );
                        else
                          return Center(
                            child: CircularProgressIndicator(
                              strokeWidth: 8,
                            ),
                          );
                      },
                    ),
                    Positioned(
                        bottom: 16,
                        right: 14,
                        child: BlocListener<MonthPickerBloc, MonthPickerState>(
                          listener: (BuildContext context, MonthPickerState state) {
                            BlocProvider.of<GajiBloc>(context).add(GetGajiEvent(
                                context, ModelFilter(monthYear: state.dateTime)));
                          },
                          child: TemplateMonthPickerNonFloating(),
                        )),
                  ],
                ),
              );
            }else{
              return CircularProgressIndicator(strokeWidth: 8);
            }
          }
      ),
    );
  }

  Future<bool> keluar() async {
    BlocProvider.of<NavigatorBloc>(context)
        .add(NavigateRemoveToDashboard(context));
    return false;
  }

  openDialog() {
    String bahasa = 'en';
    PengaturanBahasa().getDataBahasa().then((value) => bahasa = value);
    TextEditingController password = new TextEditingController();
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return WillPopScope(
            onWillPop: keluar,
            child: AlertDialog(
              shape: RoundedRectangleBorder(
                  borderRadius:
                      BorderRadius.all(Radius.circular(CustomStyle.boxRadius))),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    padding: const EdgeInsets.only(bottom: 12, top: 6),
                    width: MediaQuery.of(context).size.width,
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          TemplateFormPassword(
                            hintText: "Password",
                            controller: password,
                            color: CustomStyle.formColor,
                            radius: CustomStyle.formRadius,
                            formHeight: CustomStyle.formHeight,
                            titleText: "Password",
                          ),
                          BlocBuilder<GajiBloc, GajiState>(
                              builder: (BuildContext context, GajiState state) {
                            if (state is CekPasswordFalseState)
                              return Text(
                                state.message!,
                                style: TextStyle(
                                    fontSize: CustomStyle.fontSizeSmall,
                                    color: Colors.redAccent),
                              );
                            else
                              return Container();
                          })
                        ],
                      ),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      TemplateButton(
                        onClick: () => BlocProvider.of<NavigatorBloc>(context)
                            .add(NavigateRemoveToDashboard(context)),
                        label: bahasa == 'id' ? "TUTUP" : "CLOSE",
                        color: Colors.transparent,
                        contentColor: CustomStyle.color1,
                        fontSize: CustomStyle.fontSizeNormal,
                        bold: true,
                      ),
                      TemplateButton(
                        onClick: () => BlocProvider.of<GajiBloc>(context)
                            .add(CekPasswordEvent(context, password.text)),
                        label: bahasa=='id' ? "MASUK" : "SUBMIT",
                        color: Colors.transparent,
                        contentColor: CustomStyle.color1,
                        fontSize: CustomStyle.fontSizeNormal,
                        bold: true,
                      )
                    ],
                  )
                ],
              ),
            ),
          );
        });
  }

  Widget TemplateContainer(text1, text2) {
    return Container(
      padding: EdgeInsets.fromLTRB(14, 21, 14, 21),
      margin: EdgeInsets.only(left: 8, right: 8, top: 10),
      decoration: BoxDecoration(
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.2),
              spreadRadius: 1.6,
              blurRadius: 4,
              offset: Offset(0, 1), // changes position of shadow
            ),
          ],
          gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              stops: [
                0.0,
                0.5,
                1.0
              ],
              colors: [
                CustomStyle.color1,
                Colors.blue[400]!,
                CustomStyle.color1,
              ]),
          borderRadius: new BorderRadius.all(
            Radius.circular(10),
          )),
      child: Row(
        children: [
          Expanded(
              flex: 10,
              child: Text(
                text1,
                style: TextStyle(
                    fontSize: CustomStyle.fontSizeNormal,
                    color: Colors.white,
                    fontWeight: FontWeight.w600),
              )),
          Expanded(
              flex: 9,
              child: Text(
                text2,
                textAlign: TextAlign.right,
                style: TextStyle(
                    fontSize: CustomStyle.fontSizeNormal,
                    color: Colors.white,
                    fontWeight: FontWeight.w600),
              )),
        ],
      ),
    );
  }

  Widget TemplateRow(text1, text2, {bold = false}) {
    return Container(
      margin: EdgeInsets.only(bottom: 2),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: 4),
            child: Row(
              children: [
                Expanded(
                    flex: 8,
                    child: Text(
                      text1,
                      style: TextStyle(
                          fontSize: CustomStyle.fontSizeSmall + 1,
                          color: CustomStyle.fontColorBlack,
                          fontWeight:
                              bold ? FontWeight.w700 : FontWeight.normal),
                    )),
                Expanded(
                    flex: 9,
                    child: Text(
                      text2,
                      textAlign: TextAlign.right,
                      style: TextStyle(
                          fontSize: CustomStyle.fontSizeSmall + 1,
                          color: CustomStyle.fontColorBlack,
                          fontWeight:
                              bold ? FontWeight.w700 : FontWeight.normal),
                    )),
              ],
            ),
          ),
          SizedBox(
            height: 2,
          ),
          Divider(
            color: Colors.grey[400],
          )
        ],
      ),
    );
  }
}

class CustomExpansionTile extends StatefulWidget {
  final List<Widget> children;
  final String title;
  final String? value;
  CustomExpansionTile(this.title, this.children, {this.value});
  @override
  _CustomExpansionTileState createState() => _CustomExpansionTileState();
}

class _CustomExpansionTileState extends State<CustomExpansionTile> {
  var defaultColor = Colors.white;
  bool open = true;
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 8, right: 8, top: 10),
      decoration: BoxDecoration(
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.2),
              spreadRadius: 1.6,
              blurRadius: 4,
              offset: Offset(0, 1), // changes position of shadow
            ),
          ],
          gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              stops: [
                0.0,
                0.5,
                1.0
              ],
              colors: [
                CustomStyle.color1,
                Colors.blue[400]!,
                CustomStyle.color1,
              ]),
          borderRadius: new BorderRadius.all(
            Radius.circular(10),
          )),
      child: Theme(
        data: Theme.of(context).copyWith(
            unselectedWidgetColor: defaultColor..withOpacity(0.8),
            dividerColor: Colors.transparent),
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(10)),
          child: ExpansionTile(
            onExpansionChanged: (bool) {
              setState(() {
                if (bool) {
                  defaultColor = CustomStyle.color1;
                  open = !bool;
                } else {
                  defaultColor = Colors.white;
                  open = !bool;
                }
              });
            },
            backgroundColor: Colors.white,
            title: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  widget.title,
                  style: TextStyle(
                      color: defaultColor,
                      fontWeight: FontWeight.w600,
                      fontSize: CustomStyle.fontSizeNormal),
                ),
                widget.value != null && open
                    ? Column(
                        children: [
                          SizedBox(
                            height: 4,
                          ),
                          Align(
                              alignment: Alignment.centerRight,
                              child: Text(
                                widget.value!,
                                style: TextStyle(
                                    color: defaultColor,
                                    fontWeight: FontWeight.w600,
                                    fontSize: CustomStyle.fontSizeNormal),
                              )),
                        ],
                      )
                    : Container(),
              ],
            ),
            childrenPadding: EdgeInsets.fromLTRB(20, 4, 20, 12),
            children: widget.children,
          ),
        ),
      ),
    );
  }
}
