import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../app/config/constants.dart';
import '../../features/home/header_home_viewmodel.dart';
import 'back_button.dart';
import 'image_loader.dart';

class CustomNavigationBar extends StatelessWidget implements PreferredSizeWidget {
  final String title;
  final String? backgroundImage;
  final List<Widget> leftButtons;
  final List<Widget> rightButtons;
  final _defaultBgImage = 'assets/images/bg_header_navi.png';

  const CustomNavigationBar({
    super.key,
    required this.title,
    this.backgroundImage,
    this.leftButtons = const [CustomBackButton()],
    this.rightButtons = const [],
  });

  @override
  Size get preferredSize {
    final dispatcher = WidgetsBinding.instance.platformDispatcher;
    final view = dispatcher.implicitView ?? (dispatcher.views.isNotEmpty ? dispatcher.views.first : null);
    double paddingTop = view != null ? MediaQueryData.fromView(view).padding.top : 0.0;
    if (paddingTop == 0 && kIsWeb) {
      paddingTop = Constants.extendTopPaddingNavigation;
    }
    return Size.fromHeight(kToolbarHeight + paddingTop);
  }

  @override
  Widget build(BuildContext context) {
    final customBg = backgroundImage;
    if (customBg != null) {
      return _buildAppBar(customBg, context);
    }

    final theme = Get.find<HeaderThemeController>();
    return Obx(() {
      final bg = theme.background.value ?? _defaultBgImage;
      return _buildAppBar(bg, context);
    });
  }

  Widget _buildAppBar(String bgImage, BuildContext context) {
    double statusBarHeight = MediaQuery.of(context).padding.top;
    double extraWebPadding = 0;
    if (statusBarHeight == 0 && kIsWeb) {
      extraWebPadding = Constants.extendTopPaddingNavigation;
    }
    final double totalTopPadding = statusBarHeight + extraWebPadding;
    final bool isHttp = bgImage.startsWith('http://') || bgImage.startsWith('https://');
    final paddingTitle = (leftButtons.isNotEmpty || rightButtons.isNotEmpty) ? 72.0 : 16.0; // tránh đè lên nút 2 bên
    return Container(
      height: totalTopPadding + kToolbarHeight,
      decoration: BoxDecoration(color: bgImage.isEmpty ? Colors.white : null),
      child: Stack(
        fit: StackFit.expand,
        children: [
          if (bgImage.isNotEmpty)
            isHttp
                ? loadNetworkImage(url: bgImage, fit: BoxFit.cover, placeholderAsset: _defaultBgImage)
                : Image.asset(_defaultBgImage, fit: BoxFit.cover),
          SafeArea(
            bottom: false,
            child: Padding(
              padding: EdgeInsets.only(top: extraWebPadding),
              child: SizedBox(
                height: kToolbarHeight,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: paddingTitle),
                      child: AutoSizeText(
                        title,
                        maxLines: 1,
                        minFontSize: 12,
                        stepGranularity: 0.1,
                        overflow: TextOverflow.visible,
                        textAlign: TextAlign.center,
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w800,
                          color: Colors.white,
                        ),
                      ),
                    ),
                    if (leftButtons.isNotEmpty)
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Padding(
                          padding: const EdgeInsets.only(left: 12),
                          child: Row(mainAxisSize: MainAxisSize.min, children: leftButtons),
                        ),
                      ),
                    if (rightButtons.isNotEmpty)
                      Align(
                        alignment: Alignment.centerRight,
                        child: Padding(
                          padding: const EdgeInsets.only(right: 8),
                          child: Row(mainAxisSize: MainAxisSize.min, children: rightButtons),
                        ),
                      ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
