import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../application/auth/auth_bloc.dart';
import '../../../application/auth/logout/logout_bloc.dart';
import '../../../common/theme/theme.dart';
import '../../components/assets/assets.gen.dart';
import '../../components/dialog/logout_modal_dialog.dart';
import '../../components/toast/flushbar.dart';
import '../../router/app_router.gr.dart';

@RoutePage()
class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  @override
  void initState() {
    context.read<AuthBloc>().add(const AuthEvent.fetchCurrentUser());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<LogoutBloc, LogoutState>(
      listenWhen: (p, c) =>
          p.logoutFailureOrSuccess != c.logoutFailureOrSuccess,
      listener: (context, state) {
        state.logoutFailureOrSuccess.fold(
          () => null,
          (either) => either.fold(
            (f) {
              AppFlushbar.showAuthFailureToast(context, f);
              if (context.mounted) {
                context.router.replaceAll([const LoginRoute()]);
              }
            },
            (_) {
              if (context.mounted) {
                context.router.replaceAll([const LoginRoute()]);
              }
            },
          ),
        );
      },
      child: AutoTabsRouter(
        routes: const [
          HomeRoute(),
          TableRoute(),
          ReportRoute(),
          CustomerRoute(),
          SettingRoute(),
        ],
        builder: (context, child) {
          final tabsRouter = AutoTabsRouter.of(context);

          return Scaffold(
            body: Row(
              children: [
                // Bungkus NavigationRail dengan SingleChildScrollView
                SingleChildScrollView(
                  child: ConstrainedBox(
                    constraints: BoxConstraints(
                      minHeight: MediaQuery.of(context).size.height,
                    ),
                    child: IntrinsicHeight(
                      child: NavigationRail(
                        selectedIndex: tabsRouter.activeIndex,
                        onDestinationSelected: tabsRouter.setActiveIndex,
                        labelType: NavigationRailLabelType.none,
                        backgroundColor: AppColor.primary,
                        selectedIconTheme: const IconThemeData(
                          color: Colors.white,
                        ),
                        indicatorColor: AppColor.disabled.withOpacity(0.25),
                        indicatorShape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8.0),
                        ),
                        minExtendedWidth: 56,
                        leading: Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: Assets.images.logoWhite.image(
                            width: 40,
                            height: 40,
                            fit: BoxFit.contain,
                          ),
                        ),
                        trailing: Expanded(
                          child: Align(
                            alignment: Alignment.bottomCenter,
                            child: Padding(
                              padding: const EdgeInsets.only(bottom: 16.0),
                              child: IconButton(
                                icon: const Icon(
                                  Icons.logout,
                                  color: AppColor.disabled,
                                ),
                                onPressed: () {
                                  showDialog(
                                    context: context,
                                    builder: (context) =>
                                        const LogoutModalDialog(),
                                  );
                                },
                                tooltip: 'Logout',
                              ),
                            ),
                          ),
                        ),
                        destinations: const [
                          NavigationRailDestination(
                            icon: Icon(
                              Icons.home_outlined,
                              color: AppColor.disabled,
                            ),
                            selectedIcon: Icon(
                              Icons.home,
                              color: AppColor.white,
                            ),
                            label: Text('POS'),
                            padding: EdgeInsets.symmetric(vertical: 8),
                          ),
                          NavigationRailDestination(
                            icon: Icon(
                              Icons.table_bar_outlined,
                              color: AppColor.disabled,
                            ),
                            selectedIcon: Icon(
                              Icons.table_bar,
                              color: AppColor.white,
                            ),
                            label: Text('Meja'),
                            padding: EdgeInsets.symmetric(vertical: 8),
                          ),
                          NavigationRailDestination(
                            icon: Icon(
                              Icons.pie_chart_outline_outlined,
                              color: AppColor.disabled,
                            ),
                            selectedIcon: Icon(
                              Icons.pie_chart,
                              color: AppColor.white,
                            ),
                            label: Text('Laporan'),
                            padding: EdgeInsets.symmetric(vertical: 8),
                          ),
                          NavigationRailDestination(
                            icon: Icon(
                              Icons.person_2_outlined,
                              color: AppColor.disabled,
                            ),
                            selectedIcon: Icon(
                              Icons.person_2,
                              color: AppColor.white,
                            ),
                            label: Text('Pelanggan'),
                            padding: EdgeInsets.symmetric(vertical: 8),
                          ),
                          NavigationRailDestination(
                            icon: Icon(
                              Icons.settings_outlined,
                              color: AppColor.disabled,
                            ),
                            selectedIcon: Icon(
                              Icons.settings,
                              color: AppColor.white,
                            ),
                            label: Text('Pengaturan'),
                            padding: EdgeInsets.symmetric(vertical: 8),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                const VerticalDivider(thickness: 1, width: 1),
                // Main content area
                Expanded(child: child),
              ],
            ),
          );
        },
      ),
    );
  }
}
