import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../screen/home/header_home_viewmodel.dart';
import 'back_button.dart';
import 'image_loader.dart';

class CustomSearchNavigationBar extends StatefulWidget implements PreferredSizeWidget {
  final ValueChanged<String>? onSearchChanged;
  final String? hintText;
  final String? backgroundImage;
  final bool showBackButton;
  final List<Widget> rightButtons;

  const CustomSearchNavigationBar({
    super.key,
    this.onSearchChanged,
    this.hintText = 'Tìm kiếm...',
    this.backgroundImage, // = "assets/images/bg_header_navi.png",
    this.showBackButton = true,
    this.rightButtons = const [],
  });

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);

  @override
  _CustomSearchNavigationBarState createState() => _CustomSearchNavigationBarState();
}

class _CustomSearchNavigationBarState extends State<CustomSearchNavigationBar> {
  final TextEditingController _controller = TextEditingController();
  final _defaultBgImage = 'assets/images/bg_header_navi.png';

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.backgroundImage != null && widget.backgroundImage!.isNotEmpty) {
      return _buildAppBar(widget.backgroundImage!, context);
    }
    final theme = Get.find<HeaderThemeController>();
    return Obx(() {
      final bg = theme.background.value ?? _defaultBgImage;
      return _buildAppBar(bg, context);
    });
  }

  Widget _buildAppBar(String bgImage, BuildContext context) {
    final bool isHttp = bgImage.startsWith('http://') || bgImage.startsWith('https://');
    final double statusBarHeight = MediaQuery.of(context).padding.top;
    return SizedBox(
      height: statusBarHeight + kToolbarHeight,
      // decoration: BoxDecoration(
      //   image:
      //       widget.backgroundImage != null
      //           ? DecorationImage(image: AssetImage(widget.backgroundImage!), fit: BoxFit.cover)
      //           : null,
      //   color: widget.backgroundImage == null ? 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: Stack(
              alignment: Alignment.center,
              children: [
                Positioned(
                  left: widget.showBackButton ? 68 : 16,
                  right: widget.rightButtons.isNotEmpty ? 60 : 16,
                  child: Container(
                    height: 36,
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                    decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12)),
                    child: Row(
                      children: [
                        const Icon(Icons.search, size: 20),
                        const SizedBox(width: 4),
                        Expanded(
                          child: TextField(
                            controller: _controller,
                            onChanged: (value) {
                              setState(() {}); // Update UI for suffix icon
                              widget.onSearchChanged?.call(value);
                            },
                            decoration: InputDecoration(
                              border: InputBorder.none,
                              hintText: widget.hintText,
                              isDense: true,
                              contentPadding: EdgeInsets.zero,
                            ),
                          ),
                        ),
                        if (_controller.text.isNotEmpty)
                          GestureDetector(
                            onTap: () {
                              _controller.clear();
                              widget.onSearchChanged?.call('');
                              setState(() {});
                            },
                            child: const Icon(Icons.close, size: 20),
                          ),
                      ],
                    ),
                  ),
                ),
                if (widget.showBackButton) Positioned(left: 12, child: CustomBackButton()),
                if (widget.rightButtons.isNotEmpty)
                  Positioned(right: 12, child: Row(mainAxisSize: MainAxisSize.min, children: widget.rightButtons)),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
