import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:recording_tool/app/router/app_navigator.dart';
import 'package:recording_tool/gen/assets.gen.dart';

/// 全局页面标题栏：背景图撑满 + 居中标题 + 返回按钮。
/// 可直接赋给 [Scaffold.appBar]。
class AppPageBar extends StatelessWidget implements PreferredSizeWidget {
  const AppPageBar({
    super.key,
    this.title = '',
    this.titleWidget,
    this.backgroundImage,
    this.onBack,
    this.actions,
    this.centerTitle = true,
    this.titleSpacing,
  });

  final String title;
  final Widget? titleWidget;
  final String? backgroundImage;
  final VoidCallback? onBack;
  final List<Widget>? actions;

  /// 标题是否居中；false 时左对齐，紧随返回按钮。
  final bool centerTitle;
  final double? titleSpacing;

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

  @override
  Widget build(BuildContext context) {
    final imagePath = backgroundImage ?? Assets.images.imageAppBarBg.path;

    return AppBar(
      backgroundColor: Colors.transparent,
      elevation: 0,
      scrolledUnderElevation: 0,
      centerTitle: centerTitle,
      titleSpacing: titleSpacing,
      systemOverlayStyle: SystemUiOverlayStyle.light,
      flexibleSpace: SizedBox.expand(
        child: Image.asset(
          imagePath,
          fit: BoxFit.cover,
          alignment: Alignment.center,
        ),
      ),
      leading: IconButton(
        icon: Icon(
          Icons.chevron_left_rounded,
          color: Colors.white,
          size: 28.sp,
        ),
        onPressed: onBack ?? () => AppNavigator.pop(context: context),
      ),
      title:
          titleWidget ??
          Text(
            title,
            style: TextStyle(
              color: Colors.white,
              fontSize: 20.sp,
              fontWeight: FontWeight.w600,
              fontFamily: 'PingFang SC',
            ),
          ),
      actions: actions,
    );
  }
}

/// 兼容旧调用；内部委托 [AppPageBar]。
PreferredSizeWidget myAppBar({
  required BuildContext context,
  String title = '',
  Widget? titleWidget,
  List<Widget>? actions,
}) {
  return AppPageBar(title: title, titleWidget: titleWidget, actions: actions);
}
