import 'package:absenkuv3/Bloc/AuthBloc.dart';
import 'package:absenkuv3/Bloc/Dropdown/Akun/DropdownKelurahanBloc.dart';
import 'package:absenkuv3/Repository/Model/Akun/mDataDiri.dart';
import 'package:absenkuv3/Repository/Model/mLogin.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';

class BottomSheetKelurahan extends StatefulWidget {
  String title;
  var color;
  double fontSize;
  JenisData? initialData;
  double? formHeight;
  bool validasi;
  double marginHorizontal;
  double marginTop;
  String? idProv;
  BottomSheetKelurahan(this.title,
      {this.initialData,
      this.color = Colors.grey,
      this.fontSize = 14,
      this.formHeight,
      this.validasi = false,
      this.marginHorizontal = 0,
      this.marginTop = 11,
      this.idProv});

  @override
  _BottomSheetKelurahanState createState() => _BottomSheetKelurahanState();
}

class _BottomSheetKelurahanState extends State<BottomSheetKelurahan> {
  TextEditingController _controller = TextEditingController();
  TextEditingController _searchController = TextEditingController();
  JenisData? _selectedValue;
  List<JenisData> _filteredItems = [];

  @override
  void initState() {
    super.initState();
    if (widget.initialData != null) {
      _selectedValue = widget.initialData;
      _controller.text = widget.initialData!.nama!;
    }
    _searchController.addListener(_onSearchChanged);
  }

  @override
  void dispose() {
    _searchController.removeListener(_onSearchChanged);
    _searchController.dispose();
    super.dispose();
  }

  void _onSearchChanged() {
    // This will be handled in the modal builder where we have access to the full items list
  }

  void _showRadioModalBottomSheet(BuildContext context, List<JenisData> items) {
    final dropdownBloc = BlocProvider.of<DropdownKelurahanBloc>(context);
    _filteredItems = List.from(items); // Initialize with all items

    JenisData? tempSelectedValue = _selectedValue;

    showModalBottomSheet(
        context: context,
        showDragHandle: true,
        isScrollControlled: true, // Allow the sheet to take more space
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(
            top: Radius.circular(16.0),
          ),
        ),
        builder: (context) => BlocBuilder<AuthBloc, LoginRespon>(
                builder: (BuildContext context, LoginRespon loginRespon) {
              final String bahasa = loginRespon.dataLogin!.bahasa!;
              if (loginRespon != false) {
                return StatefulBuilder(
                  builder:
                      (BuildContext modalContext, StateSetter setModalState) {
                    return Container(
                      padding: EdgeInsets.symmetric(horizontal: 10),
                      constraints: BoxConstraints(
                        maxHeight: MediaQuery.of(context).size.height * 0.8,
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                widget.title,
                                style: TextStyle(
                                    fontSize: 18, fontWeight: FontWeight.bold),
                              ),
                              IconButton(
                                icon: Icon(Icons.close),
                                onPressed: () {
                                  _searchController.clear();
                                  Navigator.pop(modalContext);
                                },
                              ),
                            ],
                          ),
                          SizedBox(height: 10),
                          // Search bar
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 8.0),
                            child: TextField(
                              controller: _searchController,
                              decoration: InputDecoration(
                                hintText: bahasa == 'id' ? 'Cari kelurahan...' : 'Search village...',
                                prefixIcon: Icon(Icons.search),
                                border: OutlineInputBorder(
                                  borderRadius: BorderRadius.circular(8.0),
                                ),
                                contentPadding: EdgeInsets.symmetric(vertical: 12),
                              ),
                              onChanged: (value) {
                                setModalState(() {
                                  _filteredItems = items.where((item) {
                                    return item.nama!.toLowerCase().contains(value.toLowerCase());
                                  }).toList();
                                });
                              },
                            ),
                          ),
                          SizedBox(height: 10),
                          Expanded(
                            child: _filteredItems.isEmpty
                                ? Center(
                                    child: Text(
                                      bahasa == 'id' ? 'Tidak ada kelurahan ditemukan' : 'No villages found',
                                      style: TextStyle(color: Colors.grey),
                                    ),
                                  )
                                : SingleChildScrollView(
                                    child: Column(
                                      children: _filteredItems.map((item) {
                                        bool isSelected = tempSelectedValue != null &&
                                            ((item.id != null &&
                                                    tempSelectedValue!.id != null &&
                                                    item.id ==
                                                        tempSelectedValue!.id) ||
                                                (item.nama != null &&
                                                    tempSelectedValue!.nama != null &&
                                                    item.nama ==
                                                        tempSelectedValue!.nama));

                                        return Column(
                                          children: [
                                            RadioListTile<JenisData>(
                                              title: Text(item.nama ?? ''),
                                              value: item,
                                              groupValue: isSelected
                                                  ? item
                                                  : tempSelectedValue,
                                              onChanged: (JenisData? value) {
                                                setModalState(() {
                                                  tempSelectedValue = value;
                                                });
                                              },
                                            ),
                                            Divider(
                                              height: 1,
                                            ),
                                          ],
                                        );
                                      }).toList(),
                                    ),
                                  ),
                          ),
                          SizedBox(height: 16),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Expanded(
                                child: TemplateButton(
                                  onClick: () {
                                    _searchController.clear();
                                    Navigator.pop(context);
                                  },
                                  label: bahasa == 'id' ? "BATAL" : "CANCEL",
                                  color: Colors.transparent,
                                  radius: CustomStyle.boxRadius + 4,
                                  borderColor: CustomStyle.color1,
                                  contentColor: CustomStyle.color1,
                                  fontSize: CustomStyle.fontSizeNormal,
                                  bold: true,
                                ),
                              ),
                              SizedBox(width: 10),
                              Expanded(
                                child: TemplateButton(
                                  onClick: () {
                                    if (tempSelectedValue != null) {
                                      setState(() {
                                        _selectedValue = tempSelectedValue;
                                        _controller.text =
                                            tempSelectedValue!.nama!;
                                      });
                                      dropdownBloc.add(
                                          SelectDataDropdownKelurahan(
                                              tempSelectedValue!));
                                      _searchController.clear();
                                      Navigator.pop(modalContext);
                                    }
                                  },
                                  label: bahasa == 'id' ? "PILIH" : "SELECT",
                                  color: CustomStyle.color1,
                                  radius: CustomStyle.boxRadius + 4,
                                  contentColor: Colors.white,
                                  fontSize: CustomStyle.fontSizeNormal,
                                  bold: true,
                                ),
                              )
                            ],
                          ),
                          SizedBox(height: 16),
                        ],
                      ),
                    );
                  },
                );
              } else {
                return Container(
                  height: MediaQuery.of(context).size.height,
                  child: Center(
                    child: CircularProgressIndicator(
                      strokeWidth: 8,
                    ),
                  ),
                );
              }
            }));
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(
          bottom: 12,
          top: widget.marginTop,
          left: widget.marginHorizontal,
          right: widget.marginHorizontal),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          BlocBuilder<DropdownKelurahanBloc, DropdownKelurahanState>(
            builder: (BuildContext context, DropdownKelurahanState state) {
              if (state is DropdownKelurahanSuccessState) {
                if (state.selectedValue == null) {
                  _controller.text = "";
                  _selectedValue = null;
                } else {
                  _controller.text = state.selectedValue!.nama.toString();
                  _selectedValue = state.selectedValue;
                }

                return GestureDetector(
                  onTap: () => _showRadioModalBottomSheet(
                      context, state.dropdownRespon.data!),
                  child: AbsorbPointer(
                    child: TextFormField(
                      controller: _controller,
                      decoration: InputDecoration(
                        label: Row(
                          children: [
                            Text(widget.title,
                                style: TextStyle(
                                    fontSize: _controller.text.isEmpty
                                        ? widget.fontSize
                                        : 17,
                                    fontWeight: FontWeight.w400)),
                            SizedBox(width: 7),
                            Text('*',
                                style: TextStyle(
                                    color: Colors.red,
                                    fontSize: _controller.text.isEmpty
                                        ? widget.fontSize
                                        : 17)),
                          ],
                        ),
                        suffixIcon: Icon(Icons.arrow_drop_down),
                        enabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(
                              color: CustomStyle.colorLineFormDropdown),
                        ),
                        disabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(
                              color: CustomStyle.colorLineFormDropdown),
                        ),
                      ),
                      style: TextStyle(fontSize: 13),
                    ),
                  ),
                );
              } else {
                _controller.clear();
                _selectedValue = null;
                return GestureDetector(
                  onTap: () {},
                  child: AbsorbPointer(
                    child: TextFormField(
                      controller: _controller,
                      decoration: InputDecoration(
                        label: Row(
                          children: [
                            Text(widget.title,
                                style: TextStyle(
                                    fontSize: widget.fontSize,
                                    fontWeight: FontWeight.w400)),
                            SizedBox(width: 7),
                            Text('*',
                                style: TextStyle(
                                    color: Colors.red,
                                    fontSize: widget.fontSize)),
                          ],
                        ),
                        suffixIcon: Icon(Icons.arrow_drop_down),
                        enabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(
                              color: CustomStyle.colorLineFormDropdown),
                        ),
                        disabledBorder: UnderlineInputBorder(
                          borderSide: BorderSide(
                              color: CustomStyle.colorLineFormDropdown),
                        ),
                      ),
                      style: TextStyle(fontSize: 13),
                      enabled: false,
                    ),
                  ),
                );
              }
            },
          ),
        ],
      ),
    );
  }
}