import 'package:absenkuv3/Bloc/AuthBloc.dart';
import 'package:absenkuv3/Bloc/Dashboard/DashboardBloc.dart';
import 'package:absenkuv3/Bloc/MonitorAbsensi/BadgeMonitorAbsenBloc.dart';
import 'package:absenkuv3/Bloc/MonitorAbsensi/MonitorAbsenBloc.dart';
import 'package:absenkuv3/Bloc/NavigatorBloc.dart';
import 'package:absenkuv3/Bloc/klien/DashboardModeKlienBloc.dart';
import 'package:absenkuv3/Repository/Model/mLogin.dart';
import 'package:absenkuv3/Setting/PengaturanBahasa.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Modul/MonitorAbsensi/MonitorAbsensiDashboard/MonitorAbsensiDashboard.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:absenkuv3/UI/Template/templateMenu.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';

class HalamanDashboardKlien extends StatefulWidget {
  const HalamanDashboardKlien({super.key});

  @override
  State<HalamanDashboardKlien> createState() => _HalamanDashboardKlienState();
}

class _HalamanDashboardKlienState extends State<HalamanDashboardKlien> {
  @override
  void initState() {
    // _loadGridPreference();
    context.read<GridPreferenceBloc>().add(LoadGridPreference());
    super.initState();
  }

  bool isGrid = false;
  final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
      GlobalKey<RefreshIndicatorState>();
  final GlobalKey<MonitorAbsensiDashboardState> _monitorAbsensiKey =
      GlobalKey();

  DateTime? currentBackPressTime;
  Future<void> _loadGridPreference() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      isGrid =
          prefs.getBool('isGridMode') ?? false; // default false (list mode)
    });
  }

  Future<void> _saveGridPreference(bool value) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('isGridMode', value);
  }

  Future<bool> _onWillPop() async {
    DateTime now = DateTime.now();
    if (currentBackPressTime == null ||
        now.difference(currentBackPressTime!) > Duration(seconds: 2)) {
      currentBackPressTime = now;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          margin: EdgeInsets.symmetric(
              horizontal: 100, vertical: 16), // Biar ga full width
          content: Center(
            heightFactor: 1,
            child: Text(
              'Ketuk lagi untuk keluar',
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 16),
            ),
          ),
          duration: Duration(seconds: 2),
        ),
      );

      return false;
    }
    return true;
  }

  Future<void> _handleRefresh() async {
    if (_monitorAbsensiKey.currentState != null) {
      await _monitorAbsensiKey.currentState!.refreshData();
    }
    await Future.delayed(Duration(milliseconds: 500));
  }

  @override
  Widget build(BuildContext context) {
    final screenHeight = MediaQuery.of(context).size.height;
    final screenWidth = MediaQuery.of(context).size.width;
    final isPortrait =
        MediaQuery.of(context).orientation == Orientation.portrait;

    return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
        backgroundColor: CustomStyle.backgroundColor,
        body: FutureBuilder(
          future: PengaturanBahasa().dashboard(),
          builder: (context, snapshot) {
            return BlocBuilder<AuthBloc, LoginRespon>(
              builder: (context, state) {
                return LayoutBuilder(
                  builder: (context, constraints) {
                    // Responsive values
                    final headerHeight =
                        isPortrait ? screenHeight / 2.5 : screenHeight / 1.5;
                    final logoMarginTop =
                        isPortrait ? screenHeight / 6.7 : screenHeight / 4;
                    final contentMarginTop = isPortrait ? 170.0 : 180.0;
                    final logoSize = isPortrait ? 120.0 : 70.0;

                    return RefreshIndicator(
                      key: _refreshIndicatorKey,
                      onRefresh: _handleRefresh,
                      color: Colors.blue, // Warna animasi refresh
                      backgroundColor: Colors.white, // Latar belakang
                      displacement: 40.0,
                      child: SingleChildScrollView(
                        physics: AlwaysScrollableScrollPhysics(),
                        child: Stack(
                          children: [
                            // Header Background
                            Container(
                              height: headerHeight + logoSize,
                              width: screenWidth,
                              child: Stack(
                                children: [
                                  Column(
                                    children: [
                                      Container(
                                        width: double.infinity,
                                        height: headerHeight,
                                        child: Image.asset(
                                          ValueImage.headerBiruDashboard,
                                          fit: BoxFit.fitWidth,
                                        ),
                                      ),
                                    ],
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(top: logoMarginTop),
                                    padding: EdgeInsets.all(12),
                                    height: logoSize,
                                    width: screenWidth,
                                    child: Center(
                                      child: BlocBuilder<DashboardBloc,
                                          DashboardState>(
                                        builder: (BuildContext context,
                                            DashboardState state) {
                                          if (state is GetSuccess &&
                                              state.dataDashboard!.logo !=
                                                  '-') {
                                            return Image.network(
                                                state.dataDashboard!.logo!);
                                          } else {
                                            return Image.asset(
                                                ValueImage.logoDashboard);
                                          }
                                        },
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),

                            // Content
                            SafeArea(
                              child: Container(
                                padding:
                                    const EdgeInsets.fromLTRB(12, 12, 12, 16),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    // Profile Section
                                    GestureDetector(
                                      onTap: () {
                                        BlocProvider.of<NavigatorBloc>(context)
                                            .add(
                                                NavigateToHalamanDetailAkunKlien(
                                                    context));
                                      },
                                      child: Row(
                                        children: [
                                          Stack(
                                            children: [
                                              Container(
                                                decoration: BoxDecoration(
                                                  color: Colors.white,
                                                  border: Border.all(
                                                      color: Colors.grey),
                                                  borderRadius:
                                                      BorderRadius.all(
                                                    Radius.circular(120.0),
                                                  ),
                                                ),
                                                child: ClipRRect(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          120.0),
                                                  child: state.dataLogin !=
                                                              null &&
                                                          state.dataLogin!
                                                                  .foto !=
                                                              '-' &&
                                                          state.dataLogin!
                                                                  .foto !=
                                                              null
                                                      ? Image.network(
                                                          state
                                                              .dataLogin!.foto!,
                                                          height: 64,
                                                          width: 64,
                                                          fit: BoxFit.cover,
                                                          errorBuilder:
                                                              (c, obj, st) {
                                                            return Padding(
                                                              padding:
                                                                  const EdgeInsets
                                                                      .all(8.0),
                                                              child: Icon(
                                                                Icons.person,
                                                                color: Colors
                                                                    .grey[400],
                                                                size: 48,
                                                              ),
                                                            );
                                                          },
                                                        )
                                                      : Padding(
                                                          padding:
                                                              const EdgeInsets
                                                                  .all(8.0),
                                                          child: Icon(
                                                            Icons.person,
                                                            color: Colors
                                                                .grey[400],
                                                            size: 48,
                                                          ),
                                                        ),
                                                ),
                                              ),
                                            ],
                                          ),
                                          SizedBox(width: 12),
                                          Expanded(
                                            child: Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: <Widget>[
                                                Text(
                                                  state != null &&
                                                          state.dataLogin !=
                                                              null
                                                      ? state
                                                          .dataLogin!.namaUser!
                                                      : '',
                                                  style: TextStyle(
                                                    fontSize: CustomStyle
                                                        .fontSizeSubTitle,
                                                    fontWeight: FontWeight.bold,
                                                    color: Colors.black,
                                                  ),
                                                  maxLines: 2,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),

                                    SizedBox(height: contentMarginTop),
                                    BlocBuilder<GridPreferenceBloc,
                                        GridPreferenceState>(
                                      builder: (context, state) {
                                        final isGrid =
                                            state is GridPreferenceLoaded
                                                ? state.isGrid
                                                : false;

                                        return Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.end,
                                          children: [
                                            IconButton(
                                              icon: Icon(
                                                isGrid
                                                    ? Icons.view_list
                                                    : Icons.grid_view,
                                                color: Colors.orange,
                                              ),
                                              onPressed: () {
                                                context
                                                    .read<GridPreferenceBloc>()
                                                    .add(
                                                        ToggleGridPreference());
                                              },
                                            ),
                                            AnimatedSize(
                                              duration: const Duration(
                                                  milliseconds: 300),
                                              curve: Curves.easeInOut,
                                              child: AnimatedSwitcher(
                                                duration: const Duration(
                                                    milliseconds: 350),
                                                transitionBuilder:
                                                    (Widget child,
                                                        Animation<double>
                                                            animation) {
                                                  // Tambahkan kombinasi Slide dan Fade
                                                  final slideAnimation =
                                                      Tween<Offset>(
                                                    begin: const Offset(0.1, 0),
                                                    end: Offset.zero,
                                                  ).animate(CurvedAnimation(
                                                    parent: animation,
                                                    curve: Curves.easeOut,
                                                  ));

                                                  return FadeTransition(
                                                    opacity: animation,
                                                    child: SlideTransition(
                                                      position: slideAnimation,
                                                      child: child,
                                                    ),
                                                  );
                                                },
                                                child: isGrid
                                                    ? GridView.builder(
                                                        key: const ValueKey(
                                                            'grid'),
                                                        shrinkWrap: true,
                                                        physics:
                                                            const NeverScrollableScrollPhysics(),
                                                        itemCount:
                                                            _buildGridMenus()
                                                                .length,
                                                        gridDelegate:
                                                            const SliverGridDelegateWithFixedCrossAxisCount(
                                                          crossAxisCount: 3,
                                                          crossAxisSpacing: 12,
                                                          mainAxisSpacing: 12,
                                                          childAspectRatio: 0.9,
                                                        ),
                                                        itemBuilder:
                                                            (context, index) {
                                                          return _buildGridMenus()[
                                                              index];
                                                        },
                                                      )
                                                    : Column(
                                                        key: const ValueKey(
                                                            'list'),
                                                        children: _buildMenus()
                                                            .map((menu) =>
                                                                Padding(
                                                                  padding: const EdgeInsets
                                                                      .only(
                                                                      bottom:
                                                                          12.0),
                                                                  child: menu,
                                                                ))
                                                            .toList(),
                                                      ),
                                              ),
                                            ),
                                          ],
                                        );
                                      },
                                    ),
                                    SizedBox(
                                      height: 24,
                                    ),
                                    Container(
                                      width: double.infinity,
                                      child: Column(
                                        children: [
                                          Container(
                                            child: Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                Text(
                                                    'Absensi Karyawan Hari Ini',
                                                    style: TextStyle(
                                                      fontSize: CustomStyle
                                                          .fontSizeSubTitle,
                                                      fontWeight:
                                                          FontWeight.bold,
                                                    )),
                                                MonitorAbsensiDashboard(
                                                  key: _monitorAbsensiKey,
                                                ),
                                                SizedBox(
                                                  height: 30,
                                                )
                                              ],
                                            ),
                                          )
                                        ],
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                );
              },
            );
          },
        ),
      ),
    );
  }

  List<Widget> _buildMenus() {
    return [
      TemplateMenu(
        icon: ValueImage.iconIzin,
        title: 'Laporan Kinerja',
        subtitle: 'Daftar Laporan Kinerja Karyawan',
        onClick: () {
          BlocProvider.of<NavigatorBloc>(context)
              .add(NavigateToLaporanKinerjaKlien(context));
        },
      ),
      TemplateMenu(
        icon: ValueImage.iconAbsensi,
        title: 'Data Absensi',
        subtitle: 'Daftar Rekap Absensi Karyawan',
        onClick: () {
          BlocProvider.of<NavigatorBloc>(context)
              .add(NavigateToLaporanAbsensiKlien(context));
        },
      ),
      TemplateMenu(
        icon: ValueImage.iconSos,
        title: 'Data SOS',
        subtitle: 'Daftar List SOS Karyawan',
        onClick: () {
          BlocProvider.of<NavigatorBloc>(context)
              .add(NavigateToListSosKlien(context));
        },
      ),
    ];
  }

  List<Widget> _buildGridMenus() {
    return [
      TemplateMenugrid(
          'Laporan Kinerja',
          ValueImage.iconAktivitas,
          () => BlocProvider.of<NavigatorBloc>(context)
              .add(NavigateToLaporanKinerjaKlien(context))),
      TemplateMenugrid(
          'Data Absensi',
          ValueImage.iconAbsensi,
          () => BlocProvider.of<NavigatorBloc>(context)
              .add(NavigateToLaporanAbsensiKlien(context))),
      TemplateMenugrid(
          'Data SOS',
          ValueImage.iconSos,
          () => BlocProvider.of<NavigatorBloc>(context)
              .add(NavigateToListSosKlien(context))),
    ];
  }

  Widget TemplateMenugrid(String label, String image, VoidCallback onClick) {
    return GestureDetector(
      onTap: onClick,
      child: Container(
        height: 150, // Increased total height to accommodate content
        width: 100,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              height: 90,
              width: 90,
              padding: EdgeInsets.all(5),
              decoration: CustomStyle.boxDecoration,
              child: Image.asset(image, fit: BoxFit.contain),
            ),
            SizedBox(height: 4),
            Expanded(
              // Takes remaining space
              child: Text(
                label,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontSize: CustomStyle.fontSizeNormal - 1,
                  color: Colors.grey[700],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
