import 'package:absenkuv3/Bloc/BadgeNotifBloc.dart';
import 'package:absenkuv3/Bloc/NotifBloc.dart';
import 'package:absenkuv3/Repository/Model/PageModel/mNotifikasiPage.dart';
import 'package:absenkuv3/Repository/Model/mBadgepercolumn.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Modul/Notif/KomponenNotif.dart';
import 'package:absenkuv3/UI/Template/DateRangePicker/Bloc/DateRangePickerBloc.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class HalamanListNotif extends StatefulWidget {
  @override
  _HalamanListNotifState createState() => _HalamanListNotifState();
}

class _HalamanListNotifState extends State<HalamanListNotif> {
  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
  ScrollController _scrollController = new ScrollController();
  String? idSelected;
  double? initialPosition;
  Badgepercolumn? _badgepercolumn;
  bool _showBadgeList =
      false;

  @override
  void initState() {
    super.initState();
    BlocProvider.of<BadgeNotifBloc>(context).add(GetBadgepercolumn(context));
    BlocProvider.of<DateRangePickerBloc>(context).add(InitialDate());
    _scrollController.addListener(() => BlocProvider.of<NotifBloc>(context)
        .add(loadMoreEvent(_scrollController, idSelected!)));
  }

  void _toggleBadgeList() {
    setState(() {
      _showBadgeList = !_showBadgeList;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      appBar: AppBar(
        centerTitle: true,
        flexibleSpace: Image(
          image: AssetImage(ValueImage.headerBiruDashboard),
          fit: BoxFit.cover,
        ),
        backgroundColor: Colors.transparent,
        title: FutureBuilder<PageNotifikasiModel>(
          future: PengaturanBahasa().notifikasi(),
          builder: (context, snapshot) {
            return Text(
              snapshot.data == null
                  ? 'Announcement'
                  : snapshot.data!.notifikasi!.pemberitahuan!,
              style: TextStyle(fontSize: CustomStyle.fontSizeTitle),
            );
          },
        ),
      ),
      body: Stack(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                height: 50,
                width: MediaQuery.of(context).size.width,
                child: Padding(
                  padding: const EdgeInsets.only(left: 5.0, top: 5),
                  child: BlocBuilder<BadgeNotifBloc, BadgeNotifState>(
                    builder: (context, state) {
                      if (state is GetSuccessPerColumn) {
                        _badgepercolumn = state.dataColumn!;
                        if (_badgepercolumn != null &&
                            _badgepercolumn!.data!.isNotEmpty) {
                          if (idSelected == null) {
                            idSelected = _badgepercolumn!.data![0].nama!;
                            BlocProvider.of<NotifBloc>(context).add(
                                NotifDataEvent(
                                    context, _badgepercolumn!.data![0].value!));
                          }

                          if (idSelected == 'Pengumuman') {
                            initialPosition = MediaQuery.of(context).size.width;
                          } else {
                            initialPosition = 0;
                          }
                          return ListView.builder(
                              itemCount: _badgepercolumn!.data!.length,
                              scrollDirection: Axis.horizontal,
                              itemBuilder: (BuildContext context, index) {
                                return Row(
                                  children: [
                                    Row(
                                      children: [
                                        Stack(
                                          children: [
                                            Row(
                                              children: [
                                                SizedBox(
                                                  width: 2,
                                                ),
                                                ChoiceChip(
                                                  shape: RoundedRectangleBorder(
                                                      borderRadius: BorderRadius
                                                          .only(
                                                              topRight:
                                                                  Radius
                                                                      .circular(
                                                                          12),
                                                              bottomRight:
                                                                  Radius
                                                                      .circular(
                                                                          12),
                                                              topLeft: Radius
                                                                  .circular(12),
                                                              bottomLeft: Radius
                                                                  .circular(
                                                                      12))),
                                                  backgroundColor:
                                                      Colors.grey.shade200,
                                                  labelPadding: EdgeInsets.only(
                                                      left: 10, right: 10),
                                                  selectedColor:
                                                      CustomStyle.color1,
                                                  selected: idSelected ==
                                                      _badgepercolumn!
                                                          .data![index].nama,
                                                  label: Text(_badgepercolumn!
                                                          .data![index].nama ??
                                                      ''),
                                                  labelStyle: TextStyle(
                                                      color: idSelected ==
                                                              _badgepercolumn!
                                                                  .data![index]
                                                                  .nama
                                                          ? Colors.white
                                                          : CustomStyle.color1),
                                                  elevation: 1,
                                                  onSelected: (_) {
                                                    setState(() {
                                                      idSelected =
                                                          _badgepercolumn!
                                                              .data![index]
                                                              .nama!;
                                                      BlocProvider.of<
                                                                  NotifBloc>(
                                                              context)
                                                          .add(NotifDataEvent(
                                                              context,
                                                              _badgepercolumn!
                                                                  .data![index]
                                                                  .value!));
                                                    });
                                                  },
                                                ),
                                                SizedBox(
                                                  width: 11,
                                                )
                                              ],
                                            ),
                                            _badgepercolumn!
                                                        .data![index].jumlah !=
                                                    0
                                                ? Positioned(
                                                    right: 6,
                                                    top: 3,
                                                    child: Container(
                                                      child: Center(
                                                        child: Text(
                                                          _badgepercolumn!
                                                              .data![index]
                                                              .jumlah
                                                              .toString(),
                                                          style: TextStyle(
                                                              color:
                                                                  Colors.white),
                                                        ),
                                                      ),
                                                      decoration:
                                                          new BoxDecoration(
                                                        color: Colors.red,
                                                        shape: BoxShape.circle,
                                                      ),
                                                      height:
                                                          MediaQuery.of(context)
                                                                  .size
                                                                  .width *
                                                              0.05,
                                                      width:
                                                          MediaQuery.of(context)
                                                                  .size
                                                                  .width *
                                                              0.05,
                                                    ),
                                                  )
                                                : Container()
                                          ],
                                        )
                                      ],
                                    ),
                                  ],
                                );
                              });
                        } else {
                          return Container();
                        }
                      } else {
                        return Container();
                      }
                    },
                  ),
                ),
              ),
              Expanded(
                child: Padding(
                  padding:
                      const EdgeInsets.only(top: 0.0), // Adjust top padding
                  child: BlocBuilder<NotifBloc, NotifState>(
                    builder: (BuildContext context, NotifState state) {
                      if (state is SuccessNotifState ||
                          state is LoadMoreProgressState) {
                        return Stack(
                          children: <Widget>[
                            ListView.builder(
                              physics: AlwaysScrollableScrollPhysics(),
                              controller: _scrollController,
                              itemCount: state.listNotif!.length,
                              itemBuilder: (BuildContext context, index) {
                                return Column(
                                  children: [
                                    CardNotif(
                                      state.listNotif![index],
                                      '',
                                      scaffoldKey,
                                      dataCallback: (value) {
                                        if (value[0] == true) {
                                          setState(() {
                                            state.listNotif![index].flagBaca =
                                                '1';
                                            if (_badgepercolumn != null) {
                                              _badgepercolumn!.data!
                                                  .forEach((element) {
                                                if (element.nama ==
                                                    idSelected) {
                                                  element.jumlah =
                                                      (element.jumlah ?? 0) - 1;
                                                }
                                              });
                                            }
                                          });
                                        }
                                      },
                                    ),
                                    Divider(
                                      height: 1,
                                      color: Colors.grey[300],
                                    )
                                  ],
                                );
                              },
                            ),
                            if (state is LoadMoreProgressState)
                              Positioned(
                                bottom: 16,
                                child: Container(
                                  width: MediaQuery.of(context).size.width,
                                  child: Center(
                                      child: CircularProgressIndicator(
                                    strokeWidth: 8,
                                  )),
                                ),
                              )
                          ],
                        );
                      } else if (state is ProgressNotifState) {
                        return Center(
                          child: CircularProgressIndicator(
                            strokeWidth: 8,
                          ),
                        );
                      } else {
                        return Center(
                          child: Image.asset(
                            ValueImage.noData,
                            height: 250,
                          ),
                        );
                      }
                    },
                  ),
                ),
              ),
            ],
          ),
          Positioned(
            bottom: 16.0,
            right: 16.0,
            child: FloatingActionButton(
              onPressed: _toggleBadgeList,
              child: Icon(Icons.filter_list), // You can change the icon
            ),
          ),
          if (_showBadgeList &&
              _badgepercolumn != null &&
              _badgepercolumn!.data!.isNotEmpty)
            Positioned(
              bottom:
                  80.0, // Adjust this to position it correctly above the FAB
              right: 16.0,
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8.0),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.5),
                      spreadRadius: 2,
                      blurRadius: 5,
                      offset: Offset(0, 3), // changes position of shadow
                    ),
                  ],
                ),
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: _badgepercolumn!.data!.map((item) {
                      return Padding(
                        padding: const EdgeInsets.symmetric(vertical: 1.0),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            ChoiceChip(
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                              backgroundColor: Colors.grey.shade200,
                              labelPadding:
                                  EdgeInsets.symmetric(horizontal: 10),
                              selectedColor: CustomStyle.color1,
                              selected: idSelected == item.nama,
                              label: Row(
                                // Use a Row for label and badge count
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Text(item.nama ?? ''),
                                  if (item.jumlah != 0)
                                    Padding(
                                      padding: EdgeInsets.only(
                                          left: 8.0), // Add some spacing
                                      child: Container(
                                        padding: EdgeInsets.symmetric(
                                            horizontal: 6,
                                            vertical: 2), // Smaller padding
                                        decoration: BoxDecoration(
                                          color: Colors.red,
                                          shape: BoxShape.circle,
                                        ),
                                        child: Text(
                                          item.jumlah.toString(),
                                          style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 10),
                                        ),
                                      ),
                                    ),
                                ],
                              ),
                              labelStyle: TextStyle(
                                color: idSelected == item.nama
                                    ? Colors.white
                                    : CustomStyle.color1,
                              ),
                              elevation: 1,
                              onSelected: (_) {
                                setState(() {
                                  idSelected = item.nama!;
                                  BlocProvider.of<NotifBloc>(context).add(
                                      NotifDataEvent(context, item.value!));
                                  _showBadgeList =
                                      false; // Close the list after selection
                                });
                              },
                            ),
                          ],
                        ),
                      );
                    }).toList(),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }
}
