import 'package:absenkuv3/Bloc/CustomFunction.dart';
import 'package:absenkuv3/Bloc/NavigatorBloc.dart';
import 'package:absenkuv3/Bloc/NotifBloc.dart';
import 'package:absenkuv3/Bloc/SlipGaji/SlipGajiBloc.dart';
import 'package:absenkuv3/Repository/Model/PageModel/mSlipGajiPage.dart';
import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Repository/sharedPreference.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Modul/Gaji/CardItemDataGaji.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/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:url_launcher/url_launcher.dart';

class HalamanSlipGaji extends StatefulWidget {
  var data;
  HalamanSlipGaji(this.data);

  @override
  State<HalamanSlipGaji> createState() => _HalamanSlipGajiState();
}

class _HalamanSlipGajiState extends State<HalamanSlipGaji> {
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
  bool refresh = false;

  @override
  void initState() {
    super.initState();
    if(widget.data[0] == 'notif'){
      BlocProvider.of<NotifBloc>(context)
          .add(BacaNotif(widget.data[1], 'slip gaji', context));
    }
    Future.delayed(Duration(milliseconds: 500), () {
      openDialogSlipGaji();
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: keluar,
      child: FutureBuilder<PageSlipGajiModel>(
          future: PengaturanBahasa().slipGaji(),
          builder: (context, snapshot){
            if(snapshot.connectionState == ConnectionState.done){
              return BlocListener<NotifBloc, NotifState>(
                  listener: (context, stateNotifBloc) {
                    if(stateNotifBloc is SuccessBacaNotifState){
                      refresh = true;
                    }
                  },
                child: Scaffold(
                  backgroundColor: Colors.grey[200],
                  key: scaffoldKey,
                  appBar: AppBar(
                    centerTitle: true,
                    flexibleSpace: Image(
                      image: AssetImage(ValueImage.headerBiruDashboard),
                      fit: BoxFit.cover,
                    ),
                    backgroundColor: Colors.transparent,
                    title: Text(
                      snapshot.data!.menuSlipGaji!.title!,
                      style: TextStyle(fontSize: CustomStyle.fontSizeTitle),
                    ),
                  ),
                  body: Stack(
                    children: [
                      BlocBuilder<SlipGajiBloc, SlipGajiState>(
                        builder: (BuildContext context, SlipGajiState state) {
                          if (state is GetSlipGajiSuccessState)
                            return Container(
                              height: MediaQuery.of(context).size.height,
                              child: SingleChildScrollView(
                                child: Column(
                                  children: [
                                    Container(
                                      color: Colors.white,
                                      padding: EdgeInsets.fromLTRB(5, 5, 5, 11),
                                      child: Column(
                                        children: state.data!.header!
                                            .map((e) => CardItemDataGaji(
                                          e.title!,
                                          e.subtitle!,
                                          e.detail!
                                              .map((item) => TemplateRow(item.title,
                                              item.subtitle, item.fontSize,
                                              bold: item.bold))
                                              .toList(),
                                          e.bold!,
                                          e.fontSize!,
                                          e.line!,
                                          marginTop: 5,
                                        ))
                                            .toList(),
                                      ),
                                    ),
                                    Card(
                                      margin: EdgeInsets.all(13),
                                      elevation: 3,
                                      shape: RoundedRectangleBorder(
                                          borderRadius: BorderRadius.circular(17)),
                                      child: Container(
                                        margin: EdgeInsets.all(7),
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            SizedBox(height: 11),
                                            (state.data!.penerimaan == null ||
                                                state.data!.penerimaan!.length == 0)
                                                ? Container()
                                                : Column(
                                              children: state.data!.penerimaan!
                                                  .map((e) => CardItemDataGaji(
                                                e.title!,
                                                e.subtitle!,
                                                e.detail!
                                                    .map((item) =>
                                                    TemplateRow(
                                                        item.title,
                                                        item.subtitle,
                                                        item.fontSize,
                                                        bold: item.bold))
                                                    .toList(),
                                                e.bold!,
                                                e.fontSize!,
                                                e.line!,
                                                margin: true,
                                              ))
                                                  .toList(),
                                            ),
                                            SizedBox(height: state.data!.marginPerKategori),
                                            (state.data!.potongan == null ||
                                                state.data!.potongan!.length == 0)
                                                ? Container()
                                                : Column(
                                              children: state.data!.potongan!
                                                  .map((e) => CardItemDataGaji(
                                                e.title!,
                                                e.subtitle!,
                                                e.detail!
                                                    .map((item) =>
                                                    TemplateRow(
                                                        item.title,
                                                        item.subtitle,
                                                        item.fontSize,
                                                        bold: item.bold))
                                                    .toList(),
                                                e.bold!,
                                                e.fontSize!,
                                                e.line!,
                                                margin: true,
                                              ))
                                                  .toList(),
                                            ),
                                            CardItemDataGaji(
                                              state.data!.value!.title!,
                                              state.data!.value!.subtitle!,
                                              state.data!.value!.detail!
                                                  .map((item) => TemplateRow(item.title,
                                                  item.subtitle, item.fontSize,
                                                  bold: item.bold))
                                                  .toList(),
                                              state.data!.value!.bold!,
                                              state.data!.value!.fontSize!,
                                              state.data!.value!.line!,
                                              margin: true,
                                            ),
                                            (state.data!.footer == null ||
                                                state.data!.footer!.length == 0)
                                                ? Container()
                                                : Column(
                                              children: state.data!.footer!
                                                  .map((e) => CardItemDataGaji(
                                                e.title!,
                                                e.subtitle!,
                                                e.detail!
                                                    .map((item) =>
                                                    TemplateRow(
                                                        item.title,
                                                        item.subtitle,
                                                        item.fontSize,
                                                        bold: item.bold))
                                                    .toList(),
                                                e.bold!,
                                                e.fontSize!,
                                                e.line!,
                                                margin: true,
                                              ))
                                                  .toList(),
                                            ),
                                            state.data!.download!.button!
                                                ? Row(
                                              crossAxisAlignment:
                                              CrossAxisAlignment.end,
                                              children: [
                                                Expanded(
                                                  child: Container(
                                                    width: double.infinity,
                                                    margin: EdgeInsets.only(
                                                        left: 7, right: 7, top: 35),
                                                    child: TemplateButton(
                                                      enabled: true,
                                                      onClick: () async {
                                                        launcherUrl(state
                                                            .data!.download!.link!);
                                                      },
                                                      color: CustomStyle.color1,
                                                      label:
                                                      state.data!.download!.label,
                                                      fontSize: 15,
                                                      bold: true,
                                                    ),
                                                  ),
                                                ),
                                                SizedBox(width: 17),
                                                GestureDetector(
                                                  onTap: () {
                                                    Clipboard.setData(
                                                        new ClipboardData(
                                                            text: state.data!
                                                                .download!.link!));
                                                    showSnackBarDelayed(scaffoldKey,
                                                        snapshot.data!.menuSlipGaji!.linkTersalin, context);
                                                  },
                                                  child: Column(
                                                    children: [
                                                      Icon(Icons.copy),
                                                      SizedBox(height: 5),
                                                      Text(
                                                        snapshot.data!.menuSlipGaji!.copyLink!,
                                                        style: TextStyle(
                                                            fontSize: 9,
                                                            fontWeight:
                                                            FontWeight.bold),
                                                      )
                                                    ],
                                                  ),
                                                ),
                                                SizedBox(width: 9),
                                              ],
                                            )
                                                : Container(),
                                            SizedBox(height: 15)
                                          ],
                                        ),
                                      ),
                                    ),
                                    SizedBox(height: 135)
                                  ],
                                ),
                              ),
                            );
                          else if (state is SlipGajiErrorState)
                            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<SlipGajiBloc>(context).add(GetSlipGajiEvent(
                                  context, ModelFilter(monthYear: state.dateTime)));
                            },
                            child: TemplateMonthPickerNonFloating(),
                          )),
                    ],
                  ),
                ),
              );
            }else{
              return CircularProgressIndicator(strokeWidth: 8);
            }
          }
      ),
    );
  }

  Future<bool> keluar() async {
    if(widget.data[0] == 'notif'){
      Navigator.pop(context, refresh);
    }else{
      BlocProvider.of<NavigatorBloc>(context)
          .add(NavigateRemoveToDashboard(context));
    }
    return false;
  }

  openDialogSlipGaji() {
    String bahasa = 'en';
    PengaturanBahasa().getDataBahasa().then((value) => bahasa = value);
    TextEditingController password = new TextEditingController();
    showDialog(
        barrierDismissible: false,
        context: context,
        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<SlipGajiBloc, SlipGajiState>(builder:
                              (BuildContext context, SlipGajiState 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<SlipGajiBloc>(context)
                              .add(CekPasswordEvent(context, password.text));
                        },
                        label: bahasa == 'id' ? "MASUK" : "SUBMIT",
                        color: Colors.transparent,
                        contentColor: CustomStyle.color1,
                        fontSize: CustomStyle.fontSizeNormal,
                        bold: true,
                      )
                    ],
                  )
                ],
              ),
            ),
          );
        });
  }

  launcherUrl(String link) async {
    // if (await canLaunch(link)) {
    await launch(link);
    // }
  }

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