import 'package:absenkuv3/Bloc/CustomBloc.dart';
import 'package:absenkuv3/Bloc/Kpi/KpiSaya/GetDataPengajuanKpiSayaBloc.dart';
import 'package:absenkuv3/Bloc/Kpi/KpiSaya/TerimaApprovalKpiBloc.dart';
import 'package:absenkuv3/Bloc/NavigatorBloc.dart';
import 'package:absenkuv3/Bloc/NotifBloc.dart';
import 'package:absenkuv3/Repository/Model/Kpi/KpiTeam/mDataPengajuanKpi.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Modul/Kpi/KpiFinal/FinalAspekKedisipinan/FinalAspekKedisiplinan.dart';
import 'package:absenkuv3/UI/Modul/Kpi/KpiFinal/FinalAspekKepribadian/FinalAspekKepribadian.dart';
import 'package:absenkuv3/UI/Modul/Kpi/KpiFinal/FinalNilaiIndividu/FinalNilaiIndividu.dart';
import 'package:absenkuv3/UI/Modul/Kpi/KpiFinal/FinalPerfomanceIndicator/FinalPerfomanceIndicator.dart';
import 'package:absenkuv3/UI/Modul/Kpi/KpiSaya/komponen/Komponenplaning.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class HalamanDetailApprovalKpiSaya extends StatefulWidget {
  var data;

  HalamanDetailApprovalKpiSaya(this.data);

  @override
  State<HalamanDetailApprovalKpiSaya> createState() =>
      _HalamanDetailApprovalKpiSayaState();
}

class _HalamanDetailApprovalKpiSayaState
    extends State<HalamanDetailApprovalKpiSaya> {
  bool refresh = false;

  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();

  final TextEditingController _keteranganController = TextEditingController();

  @override
  void initState() {
    BlocProvider.of<GetDataPengajuanKpiSayaBloc>(context).add(
        GetDataPegajuanKpiSaya(context, widget.data![0], widget.data![1],
            widget.data![2], widget.data![3]));
    BlocProvider.of<NotifBloc>(context).add(BacaNotifNotifKpi(
      widget.data[0],
      widget.data[1],
      widget.data[2],
      widget.data[3],
      '4',
    ));
    super.initState();
  }

  Future<bool> keluar2() async {
    // Ensure there are sufficient elements
    if (widget.data.length > 5) {
      print("Data at index 5: ${widget.data[5]}");
      if (widget.data[5] == 'notif') {
        Navigator.pop(context, refresh);
      } else {
        BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
      }
    } else {
      BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: keluar2,
        child: BlocListener<NotifBloc, NotifState>(
          listener: (context, stateNotifBloc) {
            if (stateNotifBloc is SuccessBacaNotifState) {
              refresh = true;
            }
          },
          child: DefaultTabController(
            length: 4,
            child: Scaffold(
              appBar: AppBar(
                flexibleSpace: Image(
                  image: AssetImage(ValueImage.headerBiruDashboard),
                  fit: BoxFit.cover,
                ),
                backgroundColor: Colors.transparent,
                centerTitle: true,
                title: Text(
                  'Approve KPI',
                  style: TextStyle(fontSize: CustomStyle.fontSizeTitle),
                ),
              ),
              body: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    padding: EdgeInsets.symmetric(vertical: 15, horizontal: 15),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text("Periode KPI"),
                            SizedBox(
                              height: 3,
                            ),
                            Container(
                              child: Text(
                                "${getMonthName(widget.data[2])} ${widget.data[3]}",
                                style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(
                          height: 10,
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text("Nama Karyawan"),
                            SizedBox(
                              height: 3,
                            ),
                            Text(widget.data[4],
                                style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16)),
                          ],
                        )
                      ],
                    ),
                  ),
                  
                  Divider(
                    thickness: 15,
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Material(
                    child: Container(
                      height: 40,
                      child: TabBar(
                        physics: const ClampingScrollPhysics(),
                        isScrollable: true,
                        padding: EdgeInsets.only(
                            top: 0, left: 5, right: 5, bottom: 0),
                        labelPadding:
                            EdgeInsets.symmetric(vertical: 0, horizontal: 4),
                        unselectedLabelColor: CustomStyle.color1,
                        labelColor: Colors.white,
                        indicatorSize: TabBarIndicatorSize.label,
                        indicator: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            color: CustomStyle.color1),
                        tabs: [
                          Tab(
                            child: Container(
                              height: 50,
                              padding: EdgeInsets.symmetric(
                                  horizontal: 10, vertical: 5),
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(10),
                                  border: Border.all(
                                      color: CustomStyle.color1, width: 1)),
                              child: Align(
                                alignment: Alignment.center,
                                child: Text("Aspek Kinerja"),
                              ),
                            ),
                          ),
                          Tab(
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                  horizontal: 10, vertical: 5),
                              height: 50,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(10),
                                  border: Border.all(
                                      color: CustomStyle.color1, width: 1)),
                              child: Align(
                                alignment: Alignment.center,
                                child: Text("Kompetensi"),
                              ),
                            ),
                          ),
                          Tab(
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                  horizontal: 10, vertical: 5),
                              height: 50,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(10),
                                  border: Border.all(
                                      color: CustomStyle.color1, width: 1)),
                              child: Align(
                                alignment: Alignment.center,
                                child: Text("Aspek Kedisiplinan"),
                              ),
                            ),
                          ),
                          Tab(
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                  horizontal: 10, vertical: 5),
                              height: 50,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(10),
                                  border: Border.all(
                                      color: CustomStyle.color1, width: 1)),
                              child: Align(
                                alignment: Alignment.center,
                                child: Text("Nilai Individu"),
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  Expanded(
                    child: TabBarView(
                      // physics: NeverScrollableScrollPhysics(),
                      children: [
                        FinalPerfomanceIndicator([
                          widget.data![0],
                          widget.data![1],
                          widget.data![2],
                          widget.data![3]
                        ]),
                        FinalAspekKepribadian([
                          widget.data![0],
                          widget.data![1],
                          widget.data![2],
                          widget.data![3]
                        ]),
                        FinalAspekKedisiplinan([
                          widget.data![0],
                          widget.data![1],
                          widget.data![2],
                          widget.data![3]
                        ]),
                        FinalNilaiIndividu([
                          widget.data![0],
                          widget.data![1],
                          widget.data![2],
                          widget.data![3]
                        ]),
                      ],
                    ),
                  ),
                  _buildActionButtons(context)
                ],
              ),
            ),
          ),
        )
        );
  }

  Widget _buildActionButtons(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 5, vertical: 5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _buildButton(
            context,
            'Terima KPI',
            Colors.white,
            () {
              _showDialog();
            },
            isPrimary: true,
          ),
        ],
      ),
    );
  }

  void _showDialog() {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            contentPadding: EdgeInsets.zero,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10),
                  topRight: Radius.circular(10),
                  bottomLeft: Radius.circular(10),
                  bottomRight: Radius.circular(10)),
            ),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(10),
                        topRight: Radius.circular(10)),
                    color: CustomStyle.color1,
                  ),
                  height: 60,
                  width: MediaQuery.of(context).size.width,
                  child: Center(
                    child: Text("Terima KPI",
                        style: TextStyle(
                            color: Colors.white, fontWeight: FontWeight.bold)),
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                Container(
                  margin: EdgeInsets.only(left: 10),
                  child: Text('Keterangan'),
                ),
                Container(
                  margin: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
                  child: TextFormField(
                    controller: _keteranganController,
                    maxLines: 5,
                    minLines: 4,
                    decoration: InputDecoration(
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
              ],
            ),
            actions: [
              Row(
                children: [
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        Navigator.of(context).pop();
                      },
                      child: Container(
                        padding: EdgeInsets.all(14),
                        margin:
                            EdgeInsets.symmetric(horizontal: 5, vertical: 5),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(20),
                            border: Border.all(color: CustomStyle.color1)),
                        child: Center(
                            child: Text('Batal',
                                style: TextStyle(
                                    color: CustomStyle.color1,
                                    fontWeight: FontWeight.bold))),
                      ),
                    ),
                  ),
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        String keterangan = _keteranganController.text.trim();
                        if (keterangan.isEmpty) {
                          showSnackBarDelayed(scaffoldKey,
                              'Keterangan Tidak Boleh Kosong', context);
                        } else {
                          BlocProvider.of<TerimaApprovalKpiBloc>(context).add(
                              TerimaApprovalKpi(
                                  ParsingModelKaryawan(
                                      id_karyawan: widget.data![0],
                                      id_company: widget.data![1],
                                      bulan: widget.data![2],
                                      tahun: widget.data![3]),
                                  keterangan,
                                  context));
                        }
                      },
                      child: Container(
                        padding: EdgeInsets.all(14),
                        margin:
                            EdgeInsets.symmetric(horizontal: 5, vertical: 5),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(20),
                          color: CustomStyle.color1,
                        ),
                        child: Center(
                            child: Text('Submit',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold))),
                      ),
                    ),
                  ),
                ],
              )
            ],
          );
        });
  }

  Widget _buildButton(
      BuildContext context, String text, Color color, VoidCallback onTap,
      {bool isPrimary = false}) {
    return Expanded(
      child: GestureDetector(
        onTap: onTap,
        child: Container(
          margin: EdgeInsets.symmetric(horizontal: 5, vertical: 5),
          padding: EdgeInsets.all(18),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(18),
            color: isPrimary ? CustomStyle.color1 : Colors.transparent,
            border: isPrimary ? null : Border.all(color: CustomStyle.color1),
          ),
          child: Center(
            child: Text(
              text,
              style: TextStyle(
                color: color,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
