// ignore_for_file: camel_case_types, prefer_typing_uninitialized_variables

import 'package:absenkuv3/Bloc/Kpi/KpiSaya/SimpanDraftPengajuanKpiSayaBloc.dart';
import 'package:absenkuv3/Repository/Model/Kpi/KpiTeam/mDataPengajuanKpi.dart';
import 'package:absenkuv3/UI/Modul/Kpi/KpiSaya/komponen/Komponenplaning.dart';
import 'package:absenkuv3/UI/Modul/Kpi/KpiTeam/komponen/KomponenKpiPengajuanTeam.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class KomponenDetailPengajuanSaya extends StatefulWidget {
  final List<DataPengajuan> data;
  final ParsingModelKaryawan karyawan;

  KomponenDetailPengajuanSaya(this.data, this.karyawan);

  @override
  State<KomponenDetailPengajuanSaya> createState() =>
      _KomponenDetailPengajuanSayaState();
}

class _KomponenDetailPengajuanSayaState
    extends State<KomponenDetailPengajuanSaya> {
  final List<TextEditingController> controllers = [];

  @override
  void initState() {
    super.initState();
    _initializeControllers();
  }

  void _initializeControllers() {
    for (var obj in widget.data) {
      var listItems = obj.listItem;
      if (listItems != null) {
        for (var item in listItems) {
          controllers.add(TextEditingController(text: item.actualBukti));
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildHeader(),
              Divider(thickness: 15),
              _buildDataList(),
              // _buildActionButtons(context),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 15, horizontal: 15),
      margin: EdgeInsets.only(left: 5),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text("Periode KPI"),
              SizedBox(
                height: 3,
              ),
              Text(
                "${getMonthName(widget.karyawan.bulan!)} ${widget.karyawan.tahun}",
                style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16),
              ),
            ],
          ),
          SizedBox(
            height: 10,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text("Nama Karyawan"),
              SizedBox(
                height: 3,
              ),
              Text(widget.karyawan.karyawan.toString(),
                  style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16)),
            ],
          )
        ],
      ),
    );
  }

  Widget _buildDataList() {
    return ListView.builder(
      padding: EdgeInsets.only(top: 10),
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: widget.data.length,
      itemBuilder: (context, index) {
        return _buildDataItem(widget.data[index], index);
      },
    );
  }

  Widget _buildDataItem(DataPengajuan obj, int index) {
    var listItems = obj.listItem;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(
            obj.nmObject.toString(),
            style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
          ),
        ),
        Divider(),
        if (listItems != null && listItems.isNotEmpty)
          ...listItems.map((item) => _buildListItem(item)).toList(),
        Divider(thickness: 10),
      ],
    );
  }

  Widget _buildListItem(var item) {
    int controllerIndex =
        controllers.indexWhere((c) => c.text == item.actualBukti);
    var controller = controllers[controllerIndex];

    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: [
          _buildPerformanceIndicator(item),
          SizedBox(height: 15),
          _buildTargetAndWeight(item),
          SizedBox(height: 10),
          _buildScoreRows(item),
          SizedBox(height: 10),
        ],
      ),
    );
  }

  Widget _buildPerformanceIndicator(var item) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(children: [Text('Aspek Kinerja')]),
        Text(item.nmIndikator.toString(),
            style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500)),
      ],
    );
  }

  Widget _buildTargetAndWeight(var item) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Expanded(
            child: TextSub(label: 'Target', value: item.target.toString())),
        Expanded(child: TextSub(label: 'Bobot', value: item.bobot.toString())),
        Expanded(child: Container()), // Placeholder
      ],
    );
  }

  Widget _buildScoreRows(var item) {
    return Column(
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
                child: TextSub(label: 'Skor 1', value: item.poin1.toString())),
            Expanded(
                child: TextSub(label: 'Skor 2', value: item.poin2.toString())),
            Expanded(
                child: TextSub(label: 'Skor 3', value: item.poin3.toString())),
          ],
        ),
        SizedBox(height: 10),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
                child: TextSub(label: 'Skor 4', value: item.poin4.toString())),
            Expanded(
                child: TextSub(label: 'Skor 5', value: item.poin5.toString())),
            Expanded(child: Container()), // Placeholder
          ],
        ),
        SizedBox(height: 10),
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
                child: TextSub(
                    label: 'Actual', value: item.actualPoin.toString())),
            Expanded(
                child: TextSub(
                    label: 'Bukti Actual', value: item.actualBukti.toString())),
            Expanded(child: Container()), // Placeholder
          ],
        ),
      ],
    );
  }
  // Widget _build_actual(var item) {
  //   return Column(
  //     children: [
  //       Row(
  //         crossAxisAlignment: CrossAxisAlignment.start,
  //         children: [
  //           Expanded(
  //               child: TextSub(label: 'Skor 4', value: item.poin4.toString())),
  //           Expanded(
  //               child: TextSub(label: 'Skor 5', value: item.poin5.toString())),
  //           Expanded(child: Container()), // Placeholder
  //         ],
  //       ),
  //     ],
  //   );
  // }

  Widget _buildActualInput(var item, TextEditingController controller) {
    return Column(
      // crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text("Actual",
            style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500)),
        SizedBox(height: 10),
      ],
    );
  }

  Widget _buildActionButtons(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 5, vertical: 5),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _buildButton(
            context,
            'Simpan Draft',
            Colors.indigo,
            () {
              List<Map<String, dynamic>> newData = [];
              int index = 0;
              for (var obj in widget.data) {
                var listItems =
                    obj.listItem; // Use dot notation to access listItem
                if (listItems != null) {
                  for (var item in listItems) {
                    newData.add({
                      "id_pi_trx":
                          item.idPiTrx, // Use dot notation to access properties
                      "actual_poin": item.actualPoin,
                      "actual_bukti": controllers[index].text,
                    });
                    index++;
                  }
                }
              }
              BlocProvider.of<SimpanDraftPengajuanKpiSayaBloc>(context).add(
                  SimpanDraftPengajuanKpiSaya(
                      newData, widget.karyawan, context));
            },
          ),
          _buildButton(
            context,
            'Kirim Ke Atasan',
            Colors.white,
            () {
              List<Map<String, dynamic>> newData = [];
              int index = 0;
              for (var obj in widget.data) {
                var listItems =
                    obj.listItem; // Use dot notation to access listItem
                if (listItems != null) {
                  for (var item in listItems) {
                    newData.add({
                      "id_pi_trx":
                          item.idPiTrx, // Use dot notation to access properties
                      "actual_poin": item.actualPoin,
                      "actual_bukti": controllers[index].text,
                    });
                    index++;
                  }
                }
              }
              BlocProvider.of<SimpanDraftPengajuanKpiSayaBloc>(context).add(
                  PublishKeAtasan(
                      newData,
                      ParsingModelKaryawan(
                          id_karyawan: widget.karyawan.id_karyawan,
                          id_company: widget.karyawan.id_company,
                          bulan: widget.karyawan.bulan,
                          tahun: widget.karyawan.tahun),
                      context));
            },
            isPrimary: true,
          ),
        ],
      ),
    );
  }

  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 ? Colors.indigo : Colors.transparent,
            border: isPrimary ? null : Border.all(color: Colors.indigo),
          ),
          child: Center(
            child: Text(
              text,
              style: TextStyle(
                color: color,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
