// ignore_for_file: camel_case_types, prefer_typing_uninitialized_variables

// import 'package:absenkuv3/Bloc/Kpi/KpiSaya/SimpanDraftPengajuanKpiSayaBloc.dart';
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 KomponenPengajuanSaya extends StatefulWidget {
  final List<DataPengajuan> data;
  final ParsingModelKaryawan karyawan;

  KomponenPengajuanSaya(this.data, this.karyawan);

  @override
  State<KomponenPengajuanSaya> createState() => _KomponenPengajuanSayaState();
}

class _KomponenPengajuanSayaState extends State<KomponenPengajuanSaya> {
  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: [
              _buildPeriode(),
              widget.data[0].ketPeriode != null
                  ? Divider(thickness: 15)
                  : Container(),
              _buildHeader(),
              Divider(thickness: 15),
              _buildDataList(),
              widget.data[0].ignorePointer == true
                  ? Container()
                  : _buildActionButtons(context),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildPeriode() {
    return Center(
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 5, horizontal: 5),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            widget.data[0].ketPeriode != null
                ? Column(
                    children: [
                      SizedBox(
                        height: 10,
                      ),
                      Container(
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(10),
                              color: Colors.red),
                          padding: EdgeInsets.all(10),
                          child: Text(
                            widget.data[0].ketPeriode.toString(),
                            style: TextStyle(color: Colors.white),
                          )),
                    ],
                  )
                : Container(),
          ],
        ),
      ),
    );
  }

  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: 25),
          _buildActualInput(item, controller),
          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
          ],
        ),
      ],
    );
  }

  Widget _buildActualInput(var item, TextEditingController controller) {
    return Column(
      children: [
        Text("Actual",
            style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500)),
        SizedBox(height: 10),
        Container(
          width: MediaQuery.of(context).size.width,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10),
            color: widget.data[0].ignorePointer!
                ? Colors.grey.withOpacity(0.2)
                : Colors.white,
          ),
          child: Center(
            child: Wrap(
              spacing: 8.0,
              children: List<Widget>.generate(5, (i) {
                int radioValue = i + 1;
                return Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    IgnorePointer(
                      ignoring: widget.data[0].ignorePointer!,
                      child: Radio<int>(
                        value: radioValue,
                        groupValue:
                            item.actualPoin == 0 ? null : item.actualPoin,
                        onChanged: (value) {
                          setState(() {
                            item.actualPoin = value!;
                          });
                        },
                      ),
                    ),
                    Text(radioValue.toString()),
                  ],
                );
              }),
            ),
          ),
        ),
        SizedBox(height: 10),
        IgnorePointer(
          ignoring: widget.data[0].ignorePointer!,
          child: TextFormField(
            decoration: InputDecoration(
                labelText: 'Keterangan',
                hintText: 'Masukkan keterangan',
                border: OutlineInputBorder(),
                filled: widget.data[0].ignorePointer!,
                fillColor: Colors.grey.withOpacity(0.2), // Background color
                isDense: true),
            controller: controller,
            onChanged: (text) {
              setState(() {
                item.actualBukti = text;
              });
            },
          ),
        ),
      ],
    );
  }

  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,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
