// lib/widgets/bottomBarAll.dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:iconify_flutter/iconify_flutter.dart';
import 'package:iconify_flutter/icons/ep.dart';
import 'package:iconify_flutter/icons/fluent_mdl2.dart';
import 'package:iconify_flutter/icons/mdi.dart';
import 'package:iconify_flutter/icons/ri.dart';

import 'package:fl_sevengen_society_user_app/localization/localization_const.dart';
import 'package:fl_sevengen_society_user_app/theme/theme.dart';

class BottomBarAll extends StatefulWidget {
  final Widget? child;
  final int initialIndex;

  const BottomBarAll({
    super.key,
    this.child,
    this.initialIndex = 0,
  });

  @override
  State<BottomBarAll> createState() => _BottomBarAllState();
}

class _BottomBarAllState extends State<BottomBarAll> {
  int selectedIndex = 0;
  DateTime? backPressTime;

  final List<Widget> pages = const [
    Center(child: Text('Home (placeholder)')),
    Center(child: Text('Members (placeholder)')),
    Center(child: Text('Service (placeholder)')),
    Center(child: Text('Profile (placeholder)')),
  ];

  final List<Map<String, String>> sendMessage = const [
    {"image": "assets/home/system-administrator.png", "name": "Admin"},
    {"image": "assets/home/police.png", "name": "Security"},
  ];

  final List<Map<String, String>> securityAlert = const [
    {"image": "assets/home/fire-extinguisher.png", "name": "Fire Alert"},
    {"image": "assets/home/elevator.png", "name": "Stuck in Lift"},
    {"image": "assets/home/dinosaur.png", "name": "Animal Threat"},
    {"image": "assets/home/terrorist.png", "name": "Visitor Threat"},
  ];

  @override
  void initState() {
    super.initState();
    selectedIndex = widget.initialIndex;
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async => _onWillPop(context),
      child: Scaffold(
        extendBody: true,
        body: widget.child ?? pages[selectedIndex],
        bottomNavigationBar: _buildBottomBar(context),

        /// 🔴 CRITICAL FIX: Disable Hero animation
        floatingActionButton: _buildFloatingActionButton(context),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      ),
    );
  }

  Future<bool> _onWillPop(BuildContext context) async {
    final now = DateTime.now();

    if (backPressTime == null ||
        now.difference(backPressTime!) >= const Duration(seconds: 2)) {
      backPressTime = now;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          backgroundColor: blackColor,
          content: Text(
            getTranslate(context, 'exit_app.exit_text'),
            style: semibold15White,
          ),
          behavior: SnackBarBehavior.floating,
          duration: const Duration(milliseconds: 1500),
        ),
      );
      return false;
    }
    return true;
  }

  Widget _buildBottomBar(BuildContext context) {
    return BottomAppBar(
      height: 65,
      elevation: 20,
      shadowColor: blackColor,
      shape: const CircularNotchedRectangle(),
      notchMargin: 6,
      child: BottomNavigationBar(
        currentIndex: selectedIndex,
        type: BottomNavigationBarType.fixed,
        backgroundColor: whiteColor,
        selectedItemColor: primaryColor,
        unselectedItemColor: greyB4Color,
        selectedLabelStyle: semibold14Primary,
        unselectedLabelStyle: semibold14GreyB4,
        onTap: (index) => setState(() => selectedIndex = index),
        items: [
          _navItem(Ri.home_4_line, getTranslate(context, 'bottom_bar.home')),
          _navItem(Mdi.message_outline, getTranslate(context, 'bottom_bar.chats')),
          _navItem(FluentMdl2.repair, getTranslate(context, 'bottom_bar.service')),
          _navItem(Ep.user, getTranslate(context, 'bottom_bar.profile')),
        ],
      ),
    );
  }

  FloatingActionButton _buildFloatingActionButton(BuildContext context) {
    return FloatingActionButton(
      /// 🔴 HERO FIX
      heroTag: null,

      onPressed: () => _showSecurityDialog(context),
      backgroundColor: primaryColor,
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(100),
      ),
      child: const Icon(
        CupertinoIcons.checkmark_shield,
        size: 30,
        color: Colors.white,
      ),
    );
  }

  BottomNavigationBarItem _navItem(String icon, String title) {
    return BottomNavigationBarItem(
      icon: Iconify(icon, color: greyB4Color),
      activeIcon: Iconify(icon, color: primaryColor),
      label: title,
    );
  }

  void _showSecurityDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (_) => Align(
        alignment: Alignment.bottomCenter,
        child: Dialog(
          alignment: Alignment.bottomCenter,
          backgroundColor: const Color(0xFFE9F0F4),
          insetPadding: const EdgeInsets.fromLTRB(32, 8, 32, 80),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
          ),
          child: ListView(
            shrinkWrap: true,
            padding: const EdgeInsets.all(16),
            physics: const BouncingScrollPhysics(),
            children: [
              Text(
                getTranslate(context, 'bottom_bar.send_message'),
                style: semibold16Primary,
              ),
              SizedBox(height: fixPadding * 1.5),
              _buildGrid(sendMessage, onTap: () {
                Navigator.popAndPushNamed(context, '/message');
              }),
              SizedBox(height: fixPadding * 1.5),
              Text(
                getTranslate(context, 'bottom_bar.security_alert'),
                style: semibold16Primary,
              ),
              SizedBox(height: fixPadding * 1.5),
              _buildGrid(securityAlert),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildGrid(
      List<Map<String, String>> items, {
        VoidCallback? onTap,
      }) {
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: items.length,
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
        mainAxisSpacing: 16,
        crossAxisSpacing: 16,
        childAspectRatio: 1.2,
      ),
      itemBuilder: (_, index) {
        final item = items[index];
        return _gridTile(
          item['image']!,
          item['name']!,
          onTap ?? () {},
        );
      },
    );
  }

  Widget _gridTile(String image, String name, VoidCallback onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        decoration: BoxDecoration(
          color: whiteColor,
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: shadowColor.withOpacity(0.25),
              blurRadius: 6,
            ),
          ],
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.message, size: 40),
            const SizedBox(height: 5),
            Text(
              name,
              style: medium15Primary,
              overflow: TextOverflow.ellipsis,
            ),
          ],
        ),
      ),
    );
  }
}
