import 'dart:convert';
import 'dart:typed_data';
import 'package:absenkuv3/Bloc/Pkwt/DetailPkwtBloc.dart';
import 'package:absenkuv3/Bloc/Pkwt/PkwtBloc.dart';
import 'package:absenkuv3/Repository/Model/PageModel/mPkwtPage.dart';
import 'package:absenkuv3/Repository/Model/mPkwt.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Modul/Pkwt/komponen/SignatureBottomSheet.dart';
import 'package:absenkuv3/UI/Modul/Pkwt/komponen/TolakBottomSheet.dart';
import 'package:absenkuv3/UI/Modul/Pkwt/komponen/komponenPkwt.dart';
import 'package:absenkuv3/UI/Template/Snackbar/CustomSnackbar.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:signature/signature.dart';
import 'package:url_launcher/url_launcher.dart';

class HalamanDetailPkwtSaya extends StatefulWidget {
  var data;
  HalamanDetailPkwtSaya(this.data);
  @override
  State<HalamanDetailPkwtSaya> createState() => _HalamanDetailPkwtSayaState();
}

class _HalamanDetailPkwtSayaState extends State<HalamanDetailPkwtSaya> {
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();
  Uint8List? exportedImage;
  bool refresh = false;
  String eventName = '';

  SignatureController controller = SignatureController(
    penStrokeWidth: 3,
    penColor: Colors.black,
    exportBackgroundColor: Colors.transparent,
  );
  final TextEditingController alasanPenolakan = TextEditingController();
  @override
  void initState() {
    BlocProvider.of<DetailPkwtBloc>(context).add(GetDetailPkwt(widget.data[0]));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          Navigator.pop(context, [refresh, eventName]);
          return false;
        },
        child: FutureBuilder<PagePkwtModel>(
          future: PengaturanBahasa().pkwt(),
          builder: (BuildContext context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return Scaffold(
                  key: scaffoldKey,
                  appBar: AppBar(
                    centerTitle: true,
                    flexibleSpace: Image(
                      image: AssetImage(ValueImage.headerBiruDashboard),
                      fit: BoxFit.cover,
                    ),
                    backgroundColor: Colors.transparent,
                    title: Text(
                      'Detail PKWT',
                      maxLines: 2,
                      style: TextStyle(fontSize: CustomStyle.fontSizeTitle),
                    ),
                  ),
                  body: BlocBuilder<DetailPkwtBloc, DetailPkwtState>(
                      builder: (BuildContext context, DetailPkwtState state) {
                    if (state is DetailPkwtSuccess) {
                      DataPkwt dataPkwt = state.pkwtRespon.data![0];
                      print(dataPkwt.nmKaryawan);
                      return Stack(
                        children: [
                          Positioned(
                            top: 0,
                            right: 0,
                            left: 0,
                            bottom: 60,
                            child: Container(
                              width: MediaQuery.of(context).size.width,
                              child: SingleChildScrollView(
                                child: Padding(
                                  padding: const EdgeInsets.fromLTRB(
                                      16, 18, 16, 16),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              Row(
                                                children: [
                                                  Column(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment
                                                            .start,
                                                    crossAxisAlignment:
                                                        CrossAxisAlignment
                                                            .start,
                                                    children: [
                                                      Text(
                                                        dataPkwt.noPkwt!,
                                                        style: TextStyle(
                                                            fontSize: 14,
                                                            fontWeight:
                                                                FontWeight
                                                                    .bold),
                                                      ),
                                                      SizedBox(
                                                        height: 8,
                                                      ),
                                                      Text(
                                                        dataPkwt.tglPkwt!,
                                                        style: TextStyle(
                                                            fontSize: 12,
                                                            fontWeight:
                                                                FontWeight
                                                                    .w400,
                                                            color: CustomStyle
                                                                .fontColorGrey),
                                                      ),
                                                    ],
                                                  )
                                                ],
                                              )
                                            ],
                                          ),
                                          Container(
                                            margin:
                                                EdgeInsets.only(right: 15),
                                            decoration: BoxDecoration(
                                              color: Color(int.parse(
                                                  dataPkwt.warnaStatus!)),
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(3)),
                                            ),
                                            child: Padding(
                                              padding: const EdgeInsets.all(
                                                  8.0), // Sesuaikan dengan padding yang diinginkan
                                              child: Text(
                                                dataPkwt.status.toString(),
                                                style: TextStyle(
                                                    color: Color(int.parse(
                                                        dataPkwt
                                                            .warnaFont!))),
                                              ),
                                            ),
                                          )
                                        ],
                                      ),
                                      SizedBox(
                                        height: 16,
                                      ),
                                      Divider(),
                                      TemplateColumn(
                                        title: snapshot.data!.menuPkwt!.data!.namaKaryawan.toString(),
                                        value:
                                            '${dataPkwt.nik} - ${dataPkwt.nmKaryawan}',
                                      ),
                                      SizedBox(
                                        height: 16,
                                      ),
                                      TemplateColumn(
                                        title: snapshot.data!.menuPkwt!.data!.jabatan.toString(),
                                        value:
                                            '${dataPkwt.nmLevelUser} - ${dataPkwt.nmJabatan}',
                                      ),
                                      SizedBox(
                                        height: 16,
                                      ),
                                      TemplateColumn(
                                        title: snapshot.data!.menuPkwt!.data!.cabangDepartment.toString(),
                                        value:
                                            '${dataPkwt.nmCabang} - ${dataPkwt.nmDepartemen}',
                                      ),
                                      SizedBox(
                                        height: 16,
                                      ),
                                      Text(
                                        "Detail PKWT",
                                        style: TextStyle(
                                            fontSize: 12,
                                            fontWeight: FontWeight.w400,
                                            color: CustomStyle.fontColorGrey),
                                      ),
                                      CustomDocPkwt(
                                        context: context,
                                        nmKaryawan: dataPkwt.nmKaryawan,
                                        tglPkwt: dataPkwt.tglPkwt,
                                        redaksional: snapshot.data!.menuPkwt!,
                                        tapHandle: (context) {
                                          showModalBottomSheet(
                                            isScrollControlled: true,
                                            shape: RoundedRectangleBorder(
                                              borderRadius: BorderRadius.only(
                                                topLeft:
                                                    Radius.circular(30.0),
                                                topRight:
                                                    Radius.circular(30.0),
                                              ),
                                            ),
                                            backgroundColor: Colors.white,
                                            context: context,
                                            builder: (context) {
                                              return Padding(
                                                padding: EdgeInsets.all(
                                                    24), // Increased padding
                                                child: Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment
                                                          .stretch,
                                                  mainAxisSize:
                                                      MainAxisSize.min,
                                                  children: [
                                                    GestureDetector(
                                                      onTap: () async {
                                                        Uri url = Uri.parse(
                                                            dataPkwt.urlFile
                                                                .toString());
                                                        if (!await launchUrl(
                                                            url)) {
                                                          throw Exception(
                                                              'Could not launch $url');
                                                        }
                                                      },
                                                      child: Container(
                                                        padding: EdgeInsets.all(
                                                            16), // Increased padding
                                                        decoration:
                                                            BoxDecoration(
                                                          borderRadius:
                                                              BorderRadius
                                                                  .circular(
                                                                      12),
                                                          color: Colors
                                                              .grey[200],
                                                        ),
                                                        child: Row(
                                                          children: [
                                                            Container(
                                                                child: Image
                                                                    .asset(
                                                              ValueImage
                                                                  .iconViewPkwt,
                                                              width: 30,
                                                              height: 30,
                                                              color: Colors
                                                                  .indigo,
                                                            )),
                                                            SizedBox(
                                                                width: 16),
                                                            Expanded(
                                                              child: Text(
                                                                snapshot.data!.menuPkwt!.data!.lihatDokumen.toString(),
                                                                style: TextStyle(
                                                                    fontSize:
                                                                        18), // Increased text size
                                                                overflow:
                                                                    TextOverflow
                                                                        .ellipsis,
                                                              ),
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                    ),

                                                    SizedBox(
                                                        height:
                                                            24), // Increased spacing
                                                    // Container 2: Pick with File
                                                    GestureDetector(
                                                      onTap: () async {
                                                        await launcherUrl(
                                                            dataPkwt
                                                                .urlDownload
                                                                .toString());
                                                        // Uri urlDownload = Uri.parse(
                                                        //     dataPkwt.urlDownload.toString());
                                                        // if (!await launchUrl(urlDownload)) {
                                                        //   throw Exception(
                                                        //       'Could not launch $urlDownload');
                                                        // }
                                                      },
                                                      child: Container(
                                                        padding: EdgeInsets.all(
                                                            16), // Increased padding
                                                        decoration:
                                                            BoxDecoration(
                                                          borderRadius:
                                                              BorderRadius
                                                                  .circular(
                                                                      12),
                                                          color: Colors
                                                              .grey[200],
                                                        ),
                                                        child: Row(
                                                          children: [
                                                            Container(
                                                                child: Image
                                                                    .asset(
                                                              ValueImage
                                                                  .iconDownloadPkwt,
                                                              width: 30,
                                                              height: 30,
                                                              color:
                                                                  Colors.red,
                                                            )),
                                                            SizedBox(
                                                                width: 16),
                                                            Expanded(
                                                              child: Text(
                                                                snapshot.data!.menuPkwt!.data!.downloadDokumen.toString(),
                                                                style: TextStyle(
                                                                    fontSize:
                                                                        18), // Increased text size
                                                                overflow:
                                                                    TextOverflow
                                                                        .ellipsis,
                                                              ),
                                                            ),
                                                          ],
                                                        ),
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              );
                                            },
                                          );
                                        },
                                      ),
                                      SizedBox(
                                        height: 16,
                                      ),
                                      Text(
                                        "Approval",
                                        style: TextStyle(
                                            fontSize: 12,
                                            fontWeight: FontWeight.w400,
                                            color: CustomStyle.fontColorGrey),
                                      ),
                                      SizedBox(
                                        height: 8,
                                      ),
                                      Wrap(
                                        spacing: 8,
                                        direction: Axis.vertical,
                                        runSpacing: 4,
                                        children: dataPkwt.listApproval!
                                            .map(
                                              (item) => TemplateButton(
                                                label: item.statusApproval,
                                                color: Color(int.parse(
                                                    item.warnaStatus!)),
                                                heightButton: 24,
                                                radius: 4,
                                                paddingTopBottom: 0,
                                                contentColor: Color(int.parse(
                                                    item.warnaFont!)),
                                                bold: true,
                                              ),
                                            )
                                            .toList(),
                                      ),
                                      dataPkwt.statusHandle == '3'
                                          ? Container(
                                              child: Column(
                                                children: [
                                                  SizedBox(
                                                    height: 16,
                                                  ),
                                                  TemplateColumn(
                                                    title:
                                                        dataPkwt.ketTolak ==
                                                                ''
                                                            ? ''
                                                            : 'keterangan',
                                                    value: dataPkwt.ketTolak,
                                                  ),
                                                ],
                                              ),
                                            )
                                          : Container()
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          ),
                          dataPkwt.aksi == true
                              ? Positioned(
                                  bottom: 0,
                                  right: 0,
                                  left: 0,
                                  child: Container(
                                    color: Colors
                                        .white, // Atur warna latar belakang sesuai kebutuhan
                                    child: Row(
                                      children: [
                                        Expanded(
                                          child: GestureDetector(
                                            onTap: () {
                                              showBottomSheet(
                                                elevation: 20,
                                                shape: RoundedRectangleBorder(
                                                  borderRadius:
                                                      BorderRadius.only(
                                                    topLeft:
                                                        Radius.circular(30.0),
                                                    topRight:
                                                        Radius.circular(30.0),
                                                  ),
                                                ),
                                                backgroundColor: Colors.white,
                                                context: context,
                                                builder:
                                                    (BuildContext contextA) {
                                                  return WillPopScope(
                                                    onWillPop: () async {
                                                      controller.clear();
                                                      return true;
                                                    },
                                                    child: TolakBottomSheet(
                                                      redakasional: snapshot.data!.menuPkwt,
                                                      textTolak:
                                                          alasanPenolakan,
                                                      onSubmit: () {
                                                        if (alasanPenolakan
                                                            .text
                                                            .trim()
                                                            .isEmpty) {
                                                          CustomSnackBar.show(
                                                              contextA,
                                                              snapshot.data!.menuPkwt!.pesanKonfirmasi!.emptyTolak.toString(),
                                                              SnackBarType
                                                                  .warning);
                                                        } else {
                                                          BlocProvider.of<
                                                                      PkwtBloc>(
                                                                  context)
                                                              .add(tolakPwtEvent(
                                                                  context,
                                                                  scaffoldKey,
                                                                  TolakPkwtModel(
                                                                      id_pkwt:
                                                                          dataPkwt
                                                                              .idPkwt!,
                                                                      alasanTolak:
                                                                          alasanPenolakan.text)));
                                                        }
                                                      },
                                                    ),
                                                  );
                                                },
                                              );
                                            },
                                            child: Container(
                                              margin: EdgeInsets.all(8),
                                              decoration: BoxDecoration(
                                                  color: Colors.transparent,
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          30),
                                                  border: Border.all(
                                                      color: Colors.indigo)),
                                              padding: EdgeInsets.all(16),
                                              alignment: Alignment.center,
                                              child: Text(
                                                snapshot.data!.menuPkwt!.button!.btnTolak.toString(),
                                                style: TextStyle(
                                                    color: Colors.indigo[900],
                                                    fontWeight:
                                                        FontWeight.bold),
                                              ),
                                            ),
                                          ),
                                        ),
                                        Expanded(
                                          child: GestureDetector(
                                            onTap: () async {
                                              showBottomSheet(
                                                elevation: 20,
                                                shape: RoundedRectangleBorder(
                                                  borderRadius:
                                                      BorderRadius.only(
                                                    topLeft:
                                                        Radius.circular(30.0),
                                                    topRight:
                                                        Radius.circular(30.0),
                                                  ),
                                                ),
                                                backgroundColor: Colors.white,
                                                context: context,
                                                builder:
                                                    (BuildContext contextA) {
                                                  return WillPopScope(
                                                    onWillPop: () async {
                                                      controller.clear();
                                                      return true;
                                                    },
                                                    child:
                                                        SignatureBottomSheet(
                                                      controller: controller,
                                                      redakasional: snapshot.data!.menuPkwt,
                                                      onClear: () {
                                                        Navigator.of(contextA)
                                                            .pop();
                                                      },
                                                      onSubmit: () async {
                                                        exportedImage =
                                                            await controller
                                                                .toPngBytes();
                                                        if (exportedImage !=
                                                            null) {
                                                          print(dataPkwt
                                                              .nmKaryawan
                                                              .toString());
                                                          String image =
                                                              await base64Encode(
                                                                  exportedImage!);

                                                          BlocProvider.of<
                                                                      PkwtBloc>(
                                                                  context)
                                                              .add(setujuiPkwt(
                                                                  context,
                                                                  scaffoldKey,
                                                                  SetujuiPkwtModel(
                                                                      id_pkwt:
                                                                          dataPkwt
                                                                              .idPkwt!,
                                                                      image:
                                                                          image,
                                                                      no_pkwt:
                                                                          dataPkwt.noPkwt!)));
                                                        } else {
                                                          CustomSnackBar.show(
                                                              contextA,
                                                              snapshot.data!.menuPkwt!.pesanKonfirmasi!.emptyTTD.toString(),
                                                              SnackBarType
                                                                  .warning);
                                                        }
                                                      },
                                                    ),
                                                  );
                                                },
                                              );
                                            },
                                            child: Container(
                                              margin: EdgeInsets.all(
                                                  8), // Atur margin sesuai kebutuhan
                                              decoration: BoxDecoration(
                                                color: Colors.indigo[
                                                    900], // Atur warna tombol sesuai kebutuhan
                                                borderRadius:
                                                    BorderRadius.circular(30),
                                                // Membuat tombol bulat
                                              ),
                                              padding: EdgeInsets.all(
                                                  16), // Atur padding sesuai kebutuhan
                                              alignment: Alignment.center,
                                              child: Text(
                                                snapshot.data!.menuPkwt!.button!.btnSetujui.toString(),
                                                style: TextStyle(
                                                    color: Colors.white,
                                                    fontWeight:
                                                        FontWeight.bold),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                )
                              : Container(),
                        ],
                      );
                    } else if (state is DetailPkwtProgress)
                      return Container(
                          height: MediaQuery.of(context).size.height,
                          width: MediaQuery.of(context).size.width,
                          child: Center(
                              child: CircularProgressIndicator(
                            strokeWidth: 8,
                          )));
                    else
                      return Container();
                  }));
            } else {
              return Container();
            }
          },
        ));
  }

  showModalBottom(context) {
    showModalBottomSheet(
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30.0),
          topRight: Radius.circular(30.0),
        ),
      ),
      backgroundColor: Colors.white,
      context: context,
      builder: (context) {
        return Padding(
          padding: EdgeInsets.all(24), // Increased padding
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisSize: MainAxisSize.min,
            children: [
              // Container 1: Pick with Camera
              GestureDetector(
                onTap: () {},
                child: Container(
                  padding: EdgeInsets.all(16), // Increased padding
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12),
                    color: Colors.grey[200],
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.camera, size: 30), // Increased icon size
                      SizedBox(width: 16),
                      Expanded(
                        child: Text(
                          "Lihat Dokumen",
                          style: TextStyle(fontSize: 18), // Increased text size
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              SizedBox(height: 24), // Increased spacing
              // Container 2: Pick with File
              GestureDetector(
                onTap: () {},
                child: Container(
                  padding: EdgeInsets.all(16), // Increased padding
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(12),
                    color: Colors.grey[200],
                  ),
                  child: Row(
                    children: [
                      Icon(Icons.file_copy, size: 30), // Increased icon size
                      SizedBox(width: 16),
                      Expanded(
                        child: Text(
                          "Download Dokumen",
                          style: TextStyle(fontSize: 18), // Increased text size
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  launcherUrl(String link) async {
    await launch(link);
  }
}
