import 'package:absenkuv3/Bloc/Dropdown/DropdownDepartemenBloc.dart'
    as departemen;
import 'package:absenkuv3/Bloc/Dropdown/DropdownKaryawanBloc.dart';
import 'package:absenkuv3/Bloc/FilterBottomSheetBloc.dart';
import 'package:absenkuv3/Bloc/NavigatorBloc.dart';
import 'package:absenkuv3/Bloc/SearchBloc.dart';
import 'package:absenkuv3/Repository/Model/mDropdown.dart';
import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/UI/Template/Selected/Bloc/KaryawanSelectedBloc.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:absenkuv3/UI/Template/templateButton.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:absenkuv3/Bloc/Dropdown/DropdownCabangBloc.dart' as cabang;
import 'package:shimmer/shimmer.dart';

class KaryawanHeaderChip extends StatefulWidget {
  const KaryawanHeaderChip({Key? key}) : super(key: key);

  @override
  State<KaryawanHeaderChip> createState() => _KaryawanHeaderChipState();
}

class _KaryawanHeaderChipState extends State<KaryawanHeaderChip> {
  ModelFilter modelFilter = ModelFilter();
  DataDropdown? dataCabang;
  DataDropdown? dataDepartemen;
  DataDropdown? dataKaryawan;
  DataDropdown? selectedDropdown;

  @override
  Widget build(BuildContext context) {
    return MultiBlocListener(
        listeners: [
          BlocListener<cabang.DropdownCabangBloc, cabang.DropdownState>(
            listener: (BuildContext context, cabang.DropdownState state) {
              if (state is cabang.DropdownSuccessState) {
                dataCabang = state.selectedValue;
                BlocProvider.of<departemen.DropdownDepartemenBloc>(context).add(
                    departemen.GetDataDropdown(
                        idCabang: state.selectedValue?.id));
              }
            },
          ),
          BlocListener<departemen.DropdownDepartemenBloc,
              departemen.DropdownState>(
            listener: (BuildContext context, departemen.DropdownState state) {
              if (state is departemen.DropdownSuccessState) {
                dataDepartemen = state.selectedValue;
              }
            },
          ),
          BlocListener<DropdownKaryawanBloc, DropdownState>(
            listener: (BuildContext context, DropdownState state) {
              if (state is DropdownSuccessState) {
                dataKaryawan = state.selectedValue;
              }
            },
          ),
        ],
        child: FutureBuilder(
          future: PengaturanBahasa().getDataBahasa(),
          builder: (BuildContext context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              String language = snapshot.data.toString();
              return BlocBuilder<DropdownKaryawanBloc, DropdownState>(
                builder: (BuildContext context, DropdownState state) {
                  if (state is DropdownSuccessState) {
                    return Container(
                      margin: EdgeInsets.symmetric(vertical: 3, horizontal: 3),
                      child: GestureDetector(
                        onTap: () {
                          BlocProvider.of<SearchBloc>(context)
                              .add(SearchTextChanged(''));
                          BlocProvider.of<KaryawanSelectedBloc>(context)
                              .add(SelectDataKaryawan(dataKaryawan));
                          _showBottomSheet(context, language);
                        },
                        child: Chip(
                          backgroundColor: state.selectedValue == null
                              ? Colors.grey.shade200
                              : CustomStyle.color1,
                          label: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                  state.selectedValue == null
                                      ? language == 'id'
                                          ? 'Semua Pegawai'
                                          : 'All Employee'
                                      : state.selectedValue!.nama.toString(),
                                  style: TextStyle(
                                      color: state.selectedValue == null
                                          ? CustomStyle.color1
                                          : Colors.white)),
                            ],
                          ),
                        ),
                      ),
                    );
                  } else {
                    return Container(
                      height: 40,
                      width: 100,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(25)),
                      child: Shimmer.fromColors(
                        baseColor: Colors.grey[200]!,
                        highlightColor: Colors.white,
                        period: Duration(seconds: 4),
                        child: Card(
                            shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(16),
                        )),
                      ),
                    );
                  }
                },
              );
            } else {
              return Container();
            }
          },
        ));
  }

  void _showBottomSheet(BuildContext contex, String language) {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (BuildContext context) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              height: 10,
            ),
            _buildStrip(),
            _buildHeader(
                language == 'id' ? 'Pilih Pegawai' : 'Select Employee'),
            _buildSearchField(
                language == 'id' ? 'Cari Pegawai' : 'Seacrh Employee'),
            Divider(),
            Expanded(child: _buildList()),
            _buildSaveButton(language == 'id' ? 'Terapkan' : 'Apply'),
            SizedBox(
              height: 10,
            )
          ],
        );
      },
    );
  }

  Widget _buildStrip() {
    return Container(
      height: 5,
      width: 50,
      decoration: BoxDecoration(
        color: Colors.grey,
        borderRadius: BorderRadius.circular(10),
      ),
    );
  }

  Widget _buildHeader(String title) {
    return Container(
      padding: const EdgeInsets.all(8.0),
      child: Text(title, style: const TextStyle(fontSize: 18)),
    );
  }

  Widget _buildSearchField(String hint) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0),
      child: TextField(
        onChanged: (text) {
          BlocProvider.of<SearchBloc>(context)
              .add(SearchTextChanged(text.toLowerCase()));
        },
        decoration: InputDecoration(
          isDense: true,
          contentPadding: const EdgeInsets.symmetric(vertical: 8.0),
          hintText: hint,
          prefixIcon: const Icon(Icons.search),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
      ),
    );
  }

  Widget _buildList() {
    return BlocBuilder<DropdownKaryawanBloc, DropdownState>(
      builder: (BuildContext context, DropdownState state) {
        if (state is DropdownSuccessState&& state.dropdownRespon?.data != null) {
          return BlocBuilder<SearchBloc, SearchState>(
              builder: (context, searchState) {
            final filteredList = state.dropdownRespon!.data!
                .where((karyawan) => karyawan.nama!.toLowerCase().contains(
                    searchState is SearchResult ? searchState.searchText : ''))
                .toList();
            return BlocBuilder<KaryawanSelectedBloc, KaryawanSelectedState>(
              builder: (BuildContext context, KaryawanSelectedState state1) {
                return ListView.builder(
                  physics: const AlwaysScrollableScrollPhysics(),
                  itemCount: filteredList.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Column(
                      children: [
                        RadioListTile(
                          dense: true,
                          title: Text(filteredList[index].nama.toString()),
                          visualDensity: VisualDensity(vertical: -3),
                          value: filteredList[index].id,
                          groupValue: state1 is KaryawanSelectedSuccessState
                              ? state1.selectedValue?.id
                              : null,
                          onChanged: (dynamic value) {
                            selectedDropdown = filteredList.firstWhere(
                              (element) => element.id == value,
                            );
                            BlocProvider.of<KaryawanSelectedBloc>(context)
                                .add(SelectDataKaryawan(selectedDropdown));
                          },
                          controlAffinity: ListTileControlAffinity.trailing,
                        ),
                        const Divider(), // This adds a line between items
                      ],
                    );
                  },
                );
              },
            );
          });
        }else if(state is DropdownSuccessState && state.dropdownRespon?.data == null){
            return const Center(child: Text("No data available"));
        } 
        else {
          return const Center(child: CircularProgressIndicator());
        }
      },
    );
  }

  Widget _buildSaveButton(String title) {
    return TemplateButton(
      label: title,
      heightButton: 40,
      fontSize: 15,
      color: CustomStyle.color1,
      widthButton: MediaQuery.of(context).size.width - 20,
      onClick: (){
              BlocProvider.of<DropdownKaryawanBloc>(context)
              .add(SelectDataDropdown(selectedDropdown));
          modelFilter = ModelFilter(
            idCabang: dataCabang != null ? dataCabang!.id : null,
            idDepartemen: dataDepartemen != null ? dataDepartemen!.id : null,
            idPegawai: selectedDropdown != null ? selectedDropdown!.id : null,
          );
          BlocProvider.of<FilterBottomSheetBloc>(context)
              .add(setFilterBottomSheet(modelFilter));
          BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
      },
      );
    // Container(
    //   width: MediaQuery.sizeOf(context).width - 30,
    //   child: ElevatedButton(
    //     style: ElevatedButton.styleFrom(
    //         backgroundColor: Colors.blue,
    //         foregroundColor: Colors.white,
    //         shape: RoundedRectangleBorder(
    //             borderRadius: BorderRadius.circular(20))),
    //     onPressed: () {
    //       BlocProvider.of<DropdownKaryawanBloc>(context)
    //           .add(SelectDataDropdown(selectedDropdown));
    //       modelFilter = ModelFilter(
    //         idCabang: dataCabang != null ? dataCabang!.id : null,
    //         idDepartemen: dataDepartemen != null ? dataDepartemen!.id : null,
    //         idPegawai: selectedDropdown != null ? selectedDropdown!.id : null,
    //       );
    //       BlocProvider.of<FilterBottomSheetBloc>(context)
    //           .add(setFilterBottomSheet(modelFilter));
    //       BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
    //     },
    //     child: Text(title),
    //   ),
    // );
  
  }
}
