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/Setting/value_image.dart';
import 'package:absenkuv3/UI/Template/Selected/Bloc/CabangSelectedBloc.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';
import 'package:shimmer/shimmer.dart';

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

  @override
  State<CabangHeaderChip> createState() => _CabangHeaderChipState();
}

class _CabangHeaderChipState extends State<CabangHeaderChip> {
  ModelFilter modelFilter = ModelFilter();
  DataDropdown? dataCabang;
  DataDropdown? selectedDropdown;
  String _searchText = '';

  @override
  Widget build(BuildContext context) {
    return MultiBlocListener(
        listeners: [
          BlocListener<DropdownCabangBloc, DropdownState>(
            listener: (BuildContext context, DropdownState state) {
              if (state is DropdownSuccessState) {
                dataCabang = state.selectedValue;
              }
            },
          ),
        ],
        child: FutureBuilder(
          future: PengaturanBahasa().getDataBahasa(),
          builder: (BuildContext context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return BlocBuilder<DropdownCabangBloc, DropdownState>(
                builder: (BuildContext context, DropdownState state) {
                  String language = snapshot.data.toString();
                  if (state is DropdownSuccessState) {
                    return Container(
                      margin: EdgeInsets.symmetric(vertical: 3, horizontal: 3),
                      child: GestureDetector(
                        onTap: () {
                          BlocProvider.of<SearchBloc>(context)
                              .add(SearchTextChanged(''));
                          BlocProvider.of<CabangSelectedBloc>(context)
                              .add(SelectDataCabang(dataCabang));
                          _showBottomSheet(context, language);
                        },
                        child: Chip(
                          backgroundColor: state.selectedValue == null
                              ? Colors.grey.shade200
                              : CustomStyle.color1,
                          label: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(
                                  state.selectedValue == null
                                      ? snapshot.data == 'id'
                                          ? 'Semua Cabang'
                                          : 'All Branch'
                                      : 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 context, String language) {
    showModalBottomSheet(
      context: context,
      // isScrollControlled: true,
      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 Cabang' : 'Select Branch'),
            _buildSearchField(
                language == 'id' ? 'Cari Cabang...' : 'Search Branch...'),
            Divider(),
            Expanded(child: _buildList()),
            _buildButton(language == 'id' ? 'Terapkan' : 'Apply'),
            SizedBox(
              height: 10,
            )
          ],
        );
      },
    );
  }

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

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

  Widget _buildSearchField(String hint) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0),
      child: BlocBuilder<SearchBloc, SearchState>(
        builder: (context, state) {
          return 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<DropdownCabangBloc, DropdownState>(
      builder: (BuildContext context, DropdownState state) {
        if (state is DropdownSuccessState) {
          return BlocBuilder<SearchBloc, SearchState>(
            builder: (context, searchState) {
              final filteredList = state.dropdownRespon!.data!
                  .where((cabang) => cabang.nama!.toLowerCase().contains(
                      searchState is SearchResult
                          ? searchState.searchText
                          : ''))
                  .toList();
              return BlocBuilder<CabangSelectedBloc, CabangSelectedState>(
                builder: (BuildContext context, CabangSelectedState state1) {
                  if (filteredList.isEmpty) {
                    return Center(
                      child: Image.asset(
                        ValueImage.noData,
                        height: 250,
                      ),
                    );
                  } else {
                    return ListView.builder(
                      physics: const AlwaysScrollableScrollPhysics(),
                      itemCount: filteredList.length,
                      itemBuilder: (BuildContext context, int index) {
                        return Column(
                          children: [
                            RadioListTile(
                              dense: true,
                              visualDensity: VisualDensity(vertical: -3),
                              title: Text(filteredList[index].nama.toString()),
                              value: filteredList[index].id,
                              groupValue: state1 is CabangSelectedSuccessState
                                  ? state1.selectedValue?.id
                                  : null,
                              onChanged: (dynamic value) {
                                selectedDropdown = filteredList.firstWhere(
                                  (element) => element.id == value,
                                );
                                BlocProvider.of<CabangSelectedBloc>(context)
                                    .add(SelectDataCabang(selectedDropdown));
                              },
                              controlAffinity: ListTileControlAffinity.trailing,
                            ),
                            const Divider(),
                          ],
                        );
                      },
                    );
                  }
                },
              );
            },
          );
        } else {
          return const Center(child: CircularProgressIndicator());
        }
      },
    );
  }

  Widget _buildButton(String title) {
    return TemplateButton(
      label: title,
      heightButton: 40,
      fontSize: 15,
      color: CustomStyle.color1,
      widthButton: MediaQuery.of(context).size.width - 20,
      onClick: () {
        BlocProvider.of<DropdownCabangBloc>(context)
            .add(SelectDataDropdown(selectedDropdown));
        modelFilter = ModelFilter(
          idCabang: dataCabang != null ? dataCabang!.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: CustomStyle.color1,
    //         foregroundColor: Colors.white,
    //         shape: RoundedRectangleBorder(
    //             borderRadius: BorderRadius.circular(20))),
    //     onPressed: () {
    //       BlocProvider.of<DropdownCabangBloc>(context)
    //           .add(SelectDataDropdown(selectedDropdown));
    //       modelFilter = ModelFilter(
    //         idCabang: dataCabang != null ? dataCabang!.id : null,
    //       );
    //       BlocProvider.of<FilterBottomSheetBloc>(context)
    //           .add(setFilterBottomSheet(modelFilter));
    //       BlocProvider.of<NavigatorBloc>(context).add(NavigatePop(context));
    //     },
    //     child: Text(title),
    //   ),
    // );
  }
}
