import 'package:flutter/material.dart';
import 'package:window_manager/window_manager.dart';

class CustomTitleBar extends StatelessWidget {
  final VoidCallback? onSettings;
  final bool visible;

  const CustomTitleBar({super.key, this.onSettings, this.visible = true});

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: AnimatedOpacity(
        opacity: visible ? 1.0 : 0.0,
        duration: const Duration(milliseconds: 150),
        child: DragToMoveArea(
        child: SizedBox(
          height: 24,
          child: Stack(
            children: [
              if (onSettings != null)
                Positioned(
                  left: 0,
                  top: 0,
                  bottom: 0,
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      _BarButton(
                        icon: Icons.settings,
                        onTap: onSettings!,
                      ),
                    ],
                  ),
                ),
              Positioned(
                right: 0,
                top: 0,
                bottom: 0,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    _BarButton(
                      icon: Icons.horizontal_rule,
                      onTap: () => windowManager.minimize(),
                    ),
                    _BarButton(
                      icon: Icons.close,
                      onTap: () => windowManager.close(),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
        ),
      ),
    );
  }
}

class _BarButton extends StatefulWidget {
  final IconData icon;
  final VoidCallback onTap;

  const _BarButton({
    required this.icon,
    required this.onTap,
  });

  @override
  State<_BarButton> createState() => _BarButtonState();
}

class _BarButtonState extends State<_BarButton> {
  bool _hovered = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: widget.onTap,
      child: MouseRegion(
        cursor: SystemMouseCursors.click,
        onEnter: (_) => setState(() => _hovered = true),
        onExit: (_) => setState(() => _hovered = false),
        child: Container(
          width: 32,
          height: 24,
          color: _hovered ? Colors.red.withValues(alpha: 0.8) : Colors.transparent,
          child: Icon(
            widget.icon,
            color: Colors.white,
            size: 14,
          ),
        ),
      ),
    );
  }
}
