import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/core/constants/font_styles.dart';
import 'package:hamlemuhcrm/core/constants/url_services_constant.dart';
import 'package:hamlemuhcrm/core/cubits/notification_cubit.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';
import 'package:hamlemuhcrm/features/auth/login/cubit/login_cubit.dart';
import 'package:hamlemuhcrm/features/home/cubit/home_custom_cubit.dart';
import 'package:hamlemuhcrm/features/home/cubit/home_custom_state.dart';
import 'package:hamlemuhcrm/features/home/widgets/create_activity_floating_button.dart';
import 'package:hamlemuhcrm/features/home/widgets/drawer_menu.dart';

import '../../../core/constants/color_constants.dart';
import '../widgets/custom_bottom_navigation_bar.dart';
import '../widgets/exit_bottom_sheet.dart';

@immutable
class HomeCustom extends StatelessWidget {
  HomeCustom({super.key});

  final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();

  // bildirimleri listele
  void listNotification(BuildContext context) {
    context.read<NotificationCubit>().fetchNotifications(
        context.read<LoginCubit>().userfirmId,
        context.read<LoginCubit>().id,
        context.read<LoginCubit>().token);
  }

  @override
  Widget build(BuildContext context) {
    listNotification(context);
    return Scaffold(
      appBar: buildAppBar(context),
      key: scaffoldKey,
      body: BlocBuilder<HomeCustomCubit, HomeState>(
        builder: (context, state) {
          return WillPopScope(
              onWillPop: () => geriDonusTusu(context),
              child:
                  context.watch<HomeCustomCubit>().pageList[state.pageIndex]);
        },
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            _drawerHeader(context),
            const DrawerMenu(),
          ],
        ),
      ),
      bottomNavigationBar: BlocBuilder<HomeCustomCubit, HomeState>(
        builder: (context, state) {
          int mevcutIndex = 0;
          bool isButtomBar = false;
          if (state.pageIndex < 4) {
            mevcutIndex = state.pageIndex;
            isButtomBar = true;
          } else {
            isButtomBar = false;
          }
          return CustomBottomNavigationBar(
              currentIndex: mevcutIndex, isBottomBar: isButtomBar);
        },
      ),
      floatingActionButton: Visibility(
          visible: !(MediaQuery.viewInsetsOf(context).bottom != 0),
          child: const CreateActivityFloatingButton()),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    );
  }

  Future<bool> geriDonusTusu(BuildContext context) async {
    debugPrint("Navigasyon geri tuşuna dokunuldu");
    bool okey = false;
    int bodyIndex = context.read<HomeCustomCubit>().bodyindex;

    if (bodyIndex == 0) {
      bool exitConfirmed = await showAppExitSheet(context) ?? false;
      if (exitConfirmed == true) {
        okey = true;
      } else {
        okey = false;
      }
    } else {
      context.read<HomeCustomCubit>().setSecilenBodyIndeks(0);
      context.read<HomeCustomCubit>().setSecilenIndeks(0);
      okey =
          false; // Burada false olarak ayarlayarak uygulamadan çıkışın engellenmesini sağladım.
    }
    return okey;
  }

  Future<bool?> showAppExitSheet(BuildContext context) async {
    return showModalBottomSheet<bool>(
        constraints: BoxConstraints(maxHeight: context.dynamicHeight(0.2)),
        context: context,
        showDragHandle: true,
        builder: (context) {
          return ExitBottomSheet(
              onpressExit: () => Navigator.of(context).pop(true),
              onpressCancel: () => Navigator.of(context).pop(false));
        });
  }

  AppBar buildAppBar(BuildContext appBarContext) {
    return AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.black87),
        title: BlocBuilder<HomeCustomCubit, HomeState>(
          builder: (context, state) {
            return Text(context.read<HomeCustomCubit>().appBarText,
                style: FontStyles.instance.appbarTitleStyle);
          },
        ),
        centerTitle: true,
        actions: [
          _lastNotificationShortCut(appBarContext),
        ],
        // Burada state içi değerler sayfa indexleri ve sol üstte ki geri tuşuna dokunulduğunda hangi sayfaya gidileceği yazıldı.
        leading:
            BlocBuilder<HomeCustomCubit, HomeState>(builder: (context, state) {
          if (state.pageIndex != 0 &&
              state.pageIndex != 1 &&
              state.pageIndex != 2 &&
              state.pageIndex != 3) {
            // sayfalardan çıkıldığında seçili item listelerini boş listeye dönüştürüyoruz
            return IconButton(
                onPressed: () {
                  if (state.pageIndex == 4) {
                    context.read<HomeCustomCubit>().setSecilenBodyIndeks(0);
                  } else if (state.pageIndex == 5) {
                    context.read<HomeCustomCubit>().setSecilenBodyIndeks(0);
                  } else if (state.pageIndex == 6) {
                    context.read<HomeCustomCubit>().setSecilenBodyIndeks(0);
                  } else if (state.pageIndex == 7) {
                    context.read<HomeCustomCubit>().setSecilenBodyIndeks(0);
                  } else if (state.pageIndex == 8) {
                    context.read<HomeCustomCubit>().setSecilenBodyIndeks(0);
                  }
                },
                icon: const Icon(
                  Icons.arrow_back_ios_new,
                  size: 20,
                ));
          } else {
            return IconButton(
              onPressed: () {
                FocusScope.of(context).unfocus();
                if (scaffoldKey.currentState!.isDrawerOpen) {
                  scaffoldKey.currentState!.closeDrawer();
                } else {
                  scaffoldKey.currentState!.openDrawer();
                }
              },
              icon: const Icon(
                Icons.density_medium,
                color: Colors.black87,
              ),
            );
          }
        }));
  }

  Widget _lastNotificationShortCut(BuildContext appBarContext) => IconButton(
        onPressed: () {
          appBarContext.read<HomeCustomCubit>().setSecilenBodyIndeks(6);
          debugPrint('user_tip : ${appBarContext.read<LoginCubit>().tip}');
          debugPrint(
              'sayfa index : ${appBarContext.read<HomeCustomCubit>().cubitBodyIndeks}');
          debugPrint(
              'logincubit userid : ${appBarContext.read<LoginCubit>().id}');
          debugPrint(
              'logincubit api_token : ${appBarContext.read<LoginCubit>().token}');
        },
        icon: BlocBuilder<NotificationCubit, NotificationState>(
            builder: (context, state) {
          return Badge.count(
            count: state.badgeCount,
            alignment: Alignment.topLeft,
            offset: const Offset(1, 1),
            child: IconButton(
                onPressed: () => appBarContext
                    .read<HomeCustomCubit>()
                    .setSecilenBodyIndeks(6),
                icon: const Icon(Icons.notification_important)),
          );
        }),
      );

  Widget _drawerHeader(BuildContext context) {
    return DrawerHeader(
      decoration: BoxDecoration(
          color: ColorsConstants.instance.baseTheme.withOpacity(0.85)),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          InkWell(
            onTap: () {
              context.read<HomeCustomCubit>().setSecilenBodyIndeks(4);
              Navigator.pop(context);
            },
            child: CircleAvatar(
              backgroundColor: Colors.white60,
              maxRadius: 42,
              child: BlocConsumer<LoginCubit, LoginState>(
                listener: (context, state) {
                  state.isComplete;
                },
                builder: (context, state) {
                  return CircleAvatar(
                    radius: 40,
                    backgroundImage: NetworkImage(context
                                .read<LoginCubit>()
                                .userimage !=
                            ''
                        ? '${URLAPIService.instance.fileBaseURL}/upload-user/${context.read<LoginCubit>().userimage}'
                        : URLAPIService.instance.defaultPhotoUrl),
                  );
                },
              ),
            ),
          ),
          Text(
            '${context.read<LoginCubit>().ad} ${context.read<LoginCubit>().soyad}',
            style: const TextStyle(color: Colors.white),
          ),
          Text(
            context.read<LoginCubit>().unvanAd,
            style: Theme.of(context)
                .textTheme
                .bodySmall
                ?.copyWith(color: Colors.white70),
          ),
        ],
      ),
    );
  }
}
