import 'package:flutter/material.dart';
import 'package:road24_mobile/model/utils/styles/AppColors.dart';
import 'package:road24_mobile/model/utils/styles/AppStyles.dart';
import 'package:road24_mobile/utils/frequent_widgets.dart';

class CarsAppBar extends StatefulWidget implements PreferredSizeWidget {
  final String title;
  final String hintText;
  final TextEditingController? controller;

  const CarsAppBar({required this.title, this.hintText = '', this.controller});

  @override
  _CarsAppBarState createState() => _CarsAppBarState();

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

class _CarsAppBarState extends State<CarsAppBar> {
  bool isTitle = true;

  @override
  Widget build(BuildContext context) {
    if (isTitle) return appbarTitle();
    return appbarSearch();
  }

  AppBar appbarTitle() {
    return AppBar(
      backgroundColor: AppColors.appPrimaryColor,
      centerTitle: true,
      leading: FrequentWidgets.appBarBackButton(context),
      title: Text(
        widget.title,
        style: AppStyle.textStyle().copyWith(
            color: Color(0xff282828),
            fontWeight: FontWeight.w700,
            fontSize: 25.0),
        textScaleFactor: 0.9,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
      actions: widget.controller == null
          ? null
          : [
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () => setState(() => isTitle = false),
                child: Icon(
                  Icons.search,
                  size: 30,
                  color: AppColors.selectedColor,
                ),
              ),
              SizedBox(width: 8),
            ],
    );
  }

  AppBar appbarSearch() {
    return AppBar(
      brightness: Brightness.light,
      backgroundColor: Colors.white,
      elevation: 4,
      centerTitle: true,
      leading: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          widget.controller?.clear();
          setState(() => isTitle = true);
        },
        child: Icon(
          Icons.chevron_left,
          size: 30,
          color: AppColors.unSelectedColor,
        ),
      ),
      title: TextField(
        controller: widget.controller,
        cursorColor: AppColors.unSelectedColor,
        autofocus: true,
        maxLines: 1,
        decoration: InputDecoration(
          hintText: widget.hintText,
          border: InputBorder.none,
        ),
      ),
      actions: [
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () => widget.controller?.clear(),
          child: Icon(
            Icons.close,
            size: 30,
            color: AppColors.unSelectedColor,
          ),
        ),
        SizedBox(width: 8),
      ],
    );
  }
}
