import 'package:absenkuv3/Bloc/AuthBloc.dart';
import 'package:absenkuv3/Repository/Model/mLogin.dart';
import 'package:absenkuv3/UI/Template/Snackbar/CustomSnackbar.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';

// Generic Bottom Sheet Widget
class BaseBottomSheet<T, B extends BlocBase<S>, S> extends StatefulWidget {
  final String title;
  final Color color;
  final double? fontSize;
  final String? initialData;
  final double? formHeight;
  final double marginHorizontal;
  final B bloc;
  final Function(B bloc) fetchEvent;
  final Function(B bloc, T selectedItem) selectEvent;
  final String Function(T item) itemTitle;
  final Widget Function(BuildContext context, S state,
      void Function(BuildContext context, List<T> items) showModal) builder;

  BaseBottomSheet({
    required this.title,
    required this.bloc,
    required this.fetchEvent,
    required this.selectEvent,
    required this.itemTitle,
    required this.builder,
    this.initialData,
    this.color = Colors.grey,
    this.fontSize = 14,
    this.formHeight,
    this.marginHorizontal = 0,
  });

  @override
  _BaseBottomSheetState<T, B, S> createState() =>
      _BaseBottomSheetState<T, B, S>();
}

class _BaseBottomSheetState<T, B extends BlocBase<S>, S>
    extends State<BaseBottomSheet<T, B, S>> {
  late TextEditingController _controller;
  T? _selectedValue;
  late TextEditingController _searchController;
  List<T> _filteredItems = [];

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
    _searchController = TextEditingController();
    widget.fetchEvent(widget.bloc);

    if (widget.initialData != null) {
      _controller.text = widget.initialData!;
    }
  }

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

  void _filterItems(String query, List<T> items) {
    setState(() {
      _filteredItems = items.where((item) {
        final title = widget.itemTitle(item).toLowerCase();
        return title.contains(query.toLowerCase());
      }).toList();
    });
  }

  void _showModalBottomSheet(BuildContext context, List<T> items) {
    T? initialItem;
    if (widget.initialData != null) {
      try {
        initialItem = items.firstWhere(
          (item) => widget.itemTitle(item) == widget.initialData,
        );
      } catch (e) {
        initialItem = null;
      }
    }

    // Initialize filtered items with all items
    _filteredItems = List.from(items);

    showModalBottomSheet(
      showDragHandle: true,
      context: context,
      // isScrollControlled: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(16.0),
        ),
      ),
      builder: (BuildContext context) {
        return BlocBuilder<AuthBloc, LoginRespon>(
            builder: (BuildContext context, LoginRespon loginRespon) {
          if (loginRespon != false) {
            final String bahasa = loginRespon.dataLogin!.bahasa!;
            T? tempSelectedValue = _selectedValue ?? initialItem;
            return StatefulBuilder(
              builder: (BuildContext context, StateSetter setModalState) {
                if (_selectedValue == null && initialItem != null) {
                  WidgetsBinding.instance.addPostFrameCallback((_) {
                    setModalState(() {
                      _selectedValue = initialItem;
                    });
                  });
                }
                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,
                            ),
                          ),
                          GestureDetector(
                            onTap: () => Navigator.pop(context),
                            child: Icon(Icons.close),
                          )
                        ],
                      ),
                      SizedBox(height: 16),
                      // Search field
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 8.0),
                        child: TextField(
                          controller: _searchController,
                          decoration: InputDecoration(
                            hintText: bahasa == 'id' ? 'Cari...' : 'Search...',
                            prefixIcon: Icon(Icons.search),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(8.0),
                            ),
                            contentPadding: EdgeInsets.symmetric(vertical: 12),
                          ),
                          onChanged: (value) {
                            setModalState(() {
                              _filterItems(value, items);
                            });
                          },
                        ),
                      ),
                      SizedBox(height: 16),
                      Expanded(
                        child: _filteredItems.isEmpty
                            ? Center(
                                child: Text(
                                  bahasa == 'id'
                                      ? 'Tidak ada hasil ditemukan'
                                      : 'No results found',
                                  style: TextStyle(color: Colors.grey),
                                ),
                              )
                            : ListView.builder(
                                shrinkWrap: true,
                                itemCount: _filteredItems.length,
                                itemBuilder: (context, index) {
                                  final item = _filteredItems[index];
                                  return Column(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      RadioListTile(
                                        title: Text(widget.itemTitle(item)),
                                        value: item,
                                        groupValue: tempSelectedValue,
                                        onChanged: (value) {
                                          setModalState(() {
                                            tempSelectedValue = value as T;
                                          });
                                        },
                                      ),
                                      if (index != _filteredItems.length - 1)
                                        Divider(height: 1),
                                    ],
                                  );
                                },
                              ),
                      ),
                      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 =
                                        widget.itemTitle(_selectedValue as T);
                                  });
                                  widget.selectEvent(
                                      widget.bloc, _selectedValue as T);
                                  _searchController.clear();
                                  Navigator.pop(context);
                                } else {
                                  CustomSnackBar.show(
                                      context,
                                      bahasa == 'id'
                                          ? 'Oops! Belum ada yang dipilih nih'
                                          : 'Oops! Nothing has been selected yet.',
                                      SnackBarType.warning,
                                      duration: Duration(seconds: 2));
                                }
                              },
                              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: 11,
        right: widget.marginHorizontal,
        left: widget.marginHorizontal,
      ),
      child: BlocBuilder<B, S>(
        bloc: widget.bloc,
        builder: (BuildContext context, S state) {
          return widget.builder(context, state, _showModalBottomSheet);
        },
      ),
    );
  }
}