import 'package:flutter/material.dart';

@immutable
class CustomTitleBar extends StatelessWidget with PreferredSizeWidget {
  const CustomTitleBar({
    Key? key,
    required this.title,
    required this.showBack,
    this.rightHandButton,
    this.backgroundColor,
    this.beforeBack,
  }) : super(key: key);

  final Text title;
  final bool showBack;
  final IconButton? rightHandButton;
  final Color? backgroundColor;
  final Future<void> Function()? beforeBack;

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

  @override
  Widget build(BuildContext context) {
    return AppBar(
        elevation: 0,
        automaticallyImplyLeading: false,
        backgroundColor:
          backgroundColor != null ?
          backgroundColor! :
          Theme.of(context).appBarTheme.backgroundColor,
        flexibleSpace: SafeArea(
          child: Container(
            padding: const EdgeInsets.only(right: 16),
            child: Row(
              children: <Widget>[
                showBack ?
                  _backButton(context) :
                  const SizedBox.shrink(),
                showBack ?
                  const SizedBox(width: 2,) :
                  const SizedBox(width: 15),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      title,
                    ],
                  ),
                ),
                rightHandButton != null ?
                    rightHandButton! :
                    const SizedBox.shrink(),
              ],
            ),
          ),
        ),
    );
  }

  Widget _backButton(BuildContext context) {
    return IconButton(
      onPressed: () {
        if (beforeBack != null) {
          beforeBack!().then((dynamic) => Navigator.pop(context));
          return;
        }
        Navigator.pop(context);
      },
      icon: Icon(
              Icons.arrow_back,
              color: Theme.of(context).appBarTheme.iconTheme?.color,
            ),
    );
  }
}

