import 'package:absenkuv3/Bloc/Kpi/KpiTeam/PengajuanPerformanceIndikatorKpiBloc.dart';
import 'package:absenkuv3/Repository/Model/Kpi/KpiTeam/mDataPengajuanKpi.dart';
import 'package:absenkuv3/Repository/Model/Kpi/KpiTeam/mDataPengajuanKpiWithBobot.dart'
    as withbobot;
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:absenkuv3/UI/Template/templateTextFormAkun.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class KomponenCardListPengajuanKpiTeam extends StatefulWidget {
  final withbobot.ListElement data;
  final ParsingModelKaryawan dataKaryawan;
  BuildContext? ctx;
  GlobalKey<ScaffoldState>? scaffoldKey;

  KomponenCardListPengajuanKpiTeam(
      this.data, this.dataKaryawan, this.scaffoldKey, this.ctx);

  @override
  State<KomponenCardListPengajuanKpiTeam> createState() =>
      _KomponenCardListPengajuanKpiTeamState();
}

class _KomponenCardListPengajuanKpiTeamState
    extends State<KomponenCardListPengajuanKpiTeam> {
  final TextEditingController performanceIndicatorController =
      TextEditingController();
  final TextEditingController targetController = TextEditingController();
  final TextEditingController bobotController = TextEditingController();
  final TextEditingController skor1Controller = TextEditingController();
  final TextEditingController skor2Controller = TextEditingController();
  final TextEditingController skor3Controller = TextEditingController();
  final TextEditingController skor4Controller = TextEditingController();
  final TextEditingController skor5Controller = TextEditingController();
  // @override
  // void dispose() {
  //   performanceIndicatorController.dispose();
  //   targetController.dispose();
  //   bobotController.dispose();
  //   skor1Controller.dispose();
  //   skor2Controller.dispose();
  //   skor3Controller.dispose();
  //   super.dispose();
  // }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  margin: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        widget.data.nmObject.toString(),
                        style: TextStyle(
                            fontSize: 18, fontWeight: FontWeight.bold),
                      ),
                      GestureDetector(
                        onTap: () {
                          _showBottomSheet(widget.data, widget.ctx!,
                              null); // null indicates a new entry
                        },
                        child: Container(
                          padding: EdgeInsets.all(5),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20),
                              border: Border.all(color: Color(0xff3dc759))),
                          child: Row(
                            children: [
                              Icon(
                                Icons.add,
                                color: Color(0xff3dc759),
                              ),
                              Text('Tambah Data',
                                  style: TextStyle(color: Color(0xff3dc759)))
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Divider(),
                widget.data.listItem!.isNotEmpty
                    ? ListView.builder(
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        itemCount: widget.data.listItem!.length,
                        itemBuilder: (BuildContext context, index) {
                          final item = widget.data.listItem![index];
                          return Container(
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(15),
                                color: Color(0xffF2f2f7)),
                            margin: EdgeInsets.symmetric(
                                vertical: 10, horizontal: 15),
                            padding: EdgeInsets.all(11),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text('Aspek Kinerja'),
                                        PopupMenuButton<String>(
                                            onSelected: (String result) {
                                              if (result == '1') {
                                                _showBottomSheet(widget.data,
                                                    widget.ctx!, item);
                                              } else if (result == '2') {
                                                _showConfirmationDialog(context,
                                                    () {
                                                  print(item.idPiTrx);
                                                  BlocProvider.of<
                                                              PengajuanPerformanceIndikatorBloc>(
                                                          context)
                                                      .add(DeletePengajuanPerformanceIndicator(
                                                          ModelPengajuanPerformanceIndikator(
                                                            idPiTrx:
                                                                item.idPiTrx,
                                                            karyawan: widget
                                                                .dataKaryawan
                                                                .karyawan,
                                                            idCompany: widget
                                                                .dataKaryawan
                                                                .id_company,
                                                            bulan: widget
                                                                .dataKaryawan
                                                                .bulan,
                                                            tahun: widget
                                                                .dataKaryawan
                                                                .tahun,
                                                          ),
                                                          widget.ctx,
                                                          widget.scaffoldKey));
                                                });
                                              }
                                            },
                                            itemBuilder: (BuildContext
                                                    context) =>
                                                <PopupMenuEntry<String>>[
                                                  const PopupMenuItem<String>(
                                                    value: '1',
                                                    child: Text('Edit'),
                                                  ),
                                                  const PopupMenuItem<String>(
                                                    value: '2',
                                                    child: Text('Delete'),
                                                  ),
                                                ],
                                            child: Icon(
                                              Icons.more_vert_sharp,
                                              color: CustomStyle.fontColorGrey,
                                            )),
                                      ],
                                    ),
                                    Text(item.nmIndikator.toString(),
                                        style: TextStyle(
                                            fontSize: 15,
                                            fontWeight: FontWeight.w500)),
                                  ],
                                ),
                                SizedBox(
                                  height: 15,
                                ),
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Expanded(
                                        child: Container(
                                            child: TextSub(
                                      label: 'Target',
                                      value: item.target.toString(),
                                    ))), // Bagian 1
                                    Expanded(
                                        child: Container(
                                            child: TextSub(
                                      label: 'Bobot',
                                      value: item.bobot.toString(),
                                    ))), // Bagian 2
                                    Expanded(child: Container()), // Bagian 3
                                  ],
                                ),
                                SizedBox(
                                  height: 15,
                                ),
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Expanded(
                                        child: Container(
                                            child: TextSub(
                                      label: 'Skor 1',
                                      value: item.poin1.toString(),
                                    ))), // Bagian 1
                                    Expanded(
                                        child: Container(
                                            child: TextSub(
                                      label: 'Skor 2',
                                      value: item.poin2.toString(),
                                    ))), // Bagian 2
                                    Expanded(
                                        child: Container(
                                            child: TextSub(
                                      label: 'Skor 3',
                                      value: item.poin3.toString(),
                                    ))), // Bagian 3
                                  ],
                                ),
                                SizedBox(
                                  height: 10,
                                ),
                                Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Expanded(
                                        child: Container(
                                            child: TextSub(
                                      label: 'Skor 4',
                                      value: item.poin4.toString(),
                                    ))), // Bagian 1
                                    Expanded(
                                        child: Container(
                                            child: TextSub(
                                      label: 'Skor 5',
                                      value: item.poin5.toString(),
                                    ))), // Bagian 2
                                    Expanded(child: Container()), // Bagian 3
                                  ],
                                ),
                              ],
                            ),
                          );
                        },
                      )
                    : Container(
                        margin: EdgeInsets.all(20),
                        child: Center(
                          child: Text("Data masih kosong"),
                        ),
                      ),
              ],
            ),
          ),
          Divider(
            thickness: 10,
          ),
        ],
      ),
    );
  }

  void _showConfirmationDialog(BuildContext context, Function onDelete) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Konfirmasi Hapus'),
          content: Text('Apakah Anda yakin ingin menghapus item ini?'),
          actions: <Widget>[
            TextButton(
              child: Text('Batal'),
              onPressed: () {
                Navigator.of(context).pop(); // Tutup dialog
              },
            ),
            TextButton(
              child: Text('Hapus'),
              onPressed: () {
                onDelete(); // Panggil fungsi hapus
                // Navigator.of(context).pop(); // Tutup dialog setelah menghapus
              },
            ),
          ],
        );
      },
    );
  }

  void _showBottomSheet(
      withbobot.ListElement data, BuildContext ctx, withbobot.ListItem? item) {
    if (item != null) {
      performanceIndicatorController.text = item.nmIndikator.toString();
      targetController.text = item.target.toString();
      bobotController.text = item.bobot.toString();
      skor1Controller.text = item.poin1.toString();
      skor2Controller.text = item.poin2.toString();
      skor3Controller.text = item.poin3.toString();
      skor4Controller.text = item.poin4.toString();
      skor5Controller.text = item.poin5.toString();
    } else {
      performanceIndicatorController.clear();
      targetController.clear();
      bobotController.clear();
      skor1Controller.clear();
      skor2Controller.clear();
      skor3Controller.clear();
      skor4Controller.clear();
      skor5Controller.clear();
    }

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(20),
        ),
      ),
      builder: (context) {
        return Padding(
          padding: EdgeInsets.only(
            bottom: MediaQuery.of(context).viewInsets.bottom,
          ),
          child: Container(
            constraints: BoxConstraints(
              maxHeight: MediaQuery.of(context).size.height * 0.8,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Text(
                    item == null
                        ? 'Tambahkan Aspek Kinerja'
                        : 'Edit Aspek Kinerja',
                    style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold),
                  ),
                ),
                // Konten yang dapat di-scroll
                Expanded(
                  child: SingleChildScrollView(
                    child: Padding(
                      padding: const EdgeInsets.all(16.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            // padding: EdgeInsets.only(left: 10),
                            child: Container(
                              width: MediaQuery.sizeOf(context).width,
                              padding: EdgeInsets.all(10),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(10),
                                color: CustomStyle.color1.withOpacity(0.2)
                              ),
                              child: Center(
                                child: Text(
                                  widget.data.nmObject.toString(),
                                  style: TextStyle(
                                      fontSize: 20,
                                      fontWeight: FontWeight.bold),
                                ),
                              ),
                            ),
                          ),

                          SizedBox(height: 20),
                          TemplateTextFormAkun(
                            adaValidasi: true,
                            controller: performanceIndicatorController,
                            marginHorizontal: 10,
                            color: Colors.black,
                            fontSize: 13,
                            titleText: 'Aspek Kinerja',
                            // labelText: "Nama Lengkap",
                            radius: CustomStyle.formRadius,
                            // hintText: "Nama Lengkap",
                          ),

                          TemplateTextFormAkun(
                            adaValidasi: true,
                            controller: targetController,
                            marginHorizontal: 10,
                            color: Colors.black,
                            fontSize: 13,
                            titleText: 'Target',
                            // labelText: "Nama Lengkap",
                            radius: CustomStyle.formRadius,
                            // hintText: "Nama Lengkap",
                          ),
                          // SizedBox(height: 20),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              TemplateTextFormAkun(
                                adaValidasi: true,
                                controller: bobotController,
                                marginHorizontal: 10,
                                color: Colors.black,
                                fontSize: 13,
                                keyboardNumber: true,
                                formater: true,
                                titleText: 'Bobot (%)',
                                // labelText: "Nama Lengkap",
                                radius: CustomStyle.formRadius,
                                // hintText: "Nama Lengkap",
                              ),
                            ],
                          ),
                          SizedBox(height: 20),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text('Skoring',
                                  style: TextStyle(
                                      color: Colors.indigo,
                                      fontWeight: FontWeight.bold)),
                              SizedBox(height: 15),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  TemplateTextFormAkun(
                                    adaValidasi: true,
                                    controller: skor1Controller,
                                    marginHorizontal: 10,
                                    color: Colors.black,
                                    fontSize: 13,
                                    titleText: 'Skor 1',
                                    // labelText: "Nama Lengkap",
                                    radius: CustomStyle.formRadius,
                                    // hintText: "Nama Lengkap",
                                  ),
                                  TemplateTextFormAkun(
                                    adaValidasi: true,
                                    controller: skor2Controller,
                                    marginHorizontal: 10,
                                    color: Colors.black,
                                    fontSize: 13,
                                    titleText: 'Skor 2',
                                    // labelText: "Nama Lengkap",
                                    radius: CustomStyle.formRadius,
                                    // hintText: "Nama Lengkap",
                                  ),
                                  TemplateTextFormAkun(
                                    adaValidasi: true,
                                    controller: skor3Controller,
                                    marginHorizontal: 10,
                                    color: Colors.black,
                                    fontSize: 13,
                                    titleText: 'Skor 3',
                                    // labelText: "Nama Lengkap",
                                    radius: CustomStyle.formRadius,
                                    // hintText: "Nama Lengkap",
                                  ),
                                  TemplateTextFormAkun(
                                    adaValidasi: true,
                                    controller: skor4Controller,
                                    marginHorizontal: 10,
                                    color: Colors.black,
                                    fontSize: 13,
                                    titleText: 'Skor 4',
                                    // labelText: "Nama Lengkap",
                                    radius: CustomStyle.formRadius,
                                    // hintText: "Nama Lengkap",
                                  ),
                                  TemplateTextFormAkun(
                                    adaValidasi: true,
                                    controller: skor5Controller,
                                    marginHorizontal: 10,
                                    color: Colors.black,
                                    fontSize: 13,
                                    titleText: 'Skor 5',
                                    // labelText: "Nama Lengkap",
                                    radius: CustomStyle.formRadius,
                                    // hintText: "Nama Lengkap",
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Row(
                    children: [
                      Expanded(
                        child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.indigo,
                            foregroundColor: Colors.white,
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10)),
                          ),
                          onPressed: () {
                            String performanceIndicator =
                                performanceIndicatorController.text.trim();
                            String target = targetController.text.trim();
                            String bobot = bobotController.text.trim();
                            String skor1 = skor1Controller.text.trim();
                            String skor2 = skor2Controller.text.trim();
                            String skor3 = skor3Controller.text.trim();
                            String skor4 = skor4Controller.text.trim();
                            String skor5 = skor5Controller.text.trim();
                            if (item != null) {
                              if (_validateFields(performanceIndicator, target,
                                  bobot, skor1, skor2, skor3, skor4, skor5)) {
                                print("masuk");
                                BlocProvider.of<
                                            PengajuanPerformanceIndikatorBloc>(
                                        context)
                                    .add(UpdatePengajuanPerformanceIndicator(
                                        ModelPengajuanPerformanceIndikator(
                                          idPiTrx: item.idPiTrx,
                                          karyawan:
                                              widget.dataKaryawan.karyawan,
                                          idCompany:
                                              widget.dataKaryawan.id_company,
                                          bulan: widget.dataKaryawan.bulan,
                                          tahun: widget.dataKaryawan.tahun,
                                          nmObject: widget.data.nmObject,
                                          idObject: widget.data.idObjectM,
                                          noUrutObject: widget.data.noUrut,
                                          nmIndikator: performanceIndicator,
                                          target: target,
                                          bobot: bobot,
                                          poin1: skor1,
                                          poin2: skor2,
                                          poin3: skor3,
                                          poin4: skor4,
                                          poin5: skor5,
                                        ),
                                        ctx,
                                        widget.scaffoldKey));
                              } else {
                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(
                                    content:
                                        Text('Please fill all the fields.'),
                                  ),
                                );
                              }
                            } else {
                              if (_validateFields(performanceIndicator, target,
                                  bobot, skor1, skor2, skor3, skor4, skor5)) {
                                BlocProvider.of<
                                            PengajuanPerformanceIndikatorBloc>(
                                        context)
                                    .add(PengajuanPerformanceIndikator(
                                        ModelPengajuanPerformanceIndikator(
                                          karyawan:
                                              widget.dataKaryawan.karyawan,
                                          idCompany:
                                              widget.dataKaryawan.id_company,
                                          bulan: widget.dataKaryawan.bulan,
                                          tahun: widget.dataKaryawan.tahun,
                                          nmObject: widget.data.nmObject,
                                          idObject: widget.data.idObjectM,
                                          noUrutObject: widget.data.noUrut,
                                          nmIndikator: performanceIndicator,
                                          target: target,
                                          bobot: bobot,
                                          poin1: skor1,
                                          poin2: skor2,
                                          poin3: skor3,
                                          poin4: skor4,
                                          poin5: skor5,
                                        ),
                                        ctx,
                                        widget.scaffoldKey));
                              } else {
                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(
                                    content:
                                        Text('Please fill all the fields.'),
                                  ),
                                );
                              }
                            }
                            // Navigator.pop(context);
                          },
                          child: Text('SIMPAN'),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}

bool _validateFields(String performanceIndicator, String target, String bobot,
    String skor1, String skor2, String skor3, String skor4, String skor5) {
  return performanceIndicator.isNotEmpty &&
      target.isNotEmpty &&
      bobot.isNotEmpty &&
      skor1.isNotEmpty &&
      skor2.isNotEmpty &&
      skor3.isNotEmpty &&
      skor4.isNotEmpty &&
      skor5.isNotEmpty;
}

class FormTextInput extends StatelessWidget {
  final TextEditingController controller;
  final String title;

  FormTextInput({required this.controller, required this.title});

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        RichText(
          text: TextSpan(
            children: [
              TextSpan(
                text: title,
                style: TextStyle(
                  color: Colors.black, // Warna teks normal
                  fontSize: 16.0, // Ukuran font sesuai kebutuhan
                ),
              ),
              TextSpan(
                text: ' *',
                style: TextStyle(
                  color: Colors.red, // Warna * menjadi merah
                  fontSize: 16.0, // Ukuran font sesuai kebutuhan
                ),
              ),
            ],
          ),
        ), // Jarak antara label dan TextField
        TextField(
          controller: controller,
          decoration: InputDecoration(
            isDense: true,
            // border: OutlineInputBorder(),
          ),
        ),
      ],
    );
  }
}

class TextSub extends StatelessWidget {
  final String label;
  final String value;

  const TextSub({
    Key? key,
    required this.label,
    required this.value,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: TextStyle(
              color: CustomStyle.fontColorGrey,
              fontSize: 12,
              fontWeight: FontWeight.w400),
        ),
        // SizedBox(
        //   height: 8,
        // ),
        Text(
          value.toString(),
          style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
        ),
      ],
    );
  }
}
