import 'dart:async';

import 'package:flutter/material.dart';
import 'package:moonwell_launcher/app/theme/mw_theme.dart';
import 'package:window_manager/window_manager.dart';

class WindowTitleBar extends StatelessWidget {
  const WindowTitleBar({super.key});

  @override
  Widget build(BuildContext context) {
    final cs = Theme.of(context).colorScheme;

    return GestureDetector(
      onPanStart: (_) => windowManager.startDragging(),
      child: SizedBox(
        height: 36,
        child: Row(
          children: [
            const Spacer(),
            _TitleBarButton(
              icon: Icons.remove,
              onTap: () => windowManager.minimize(),
              color: cs.onSurface,
            ),
            _TitleBarButton(
              icon: Icons.crop_square,
              onTap: () {
                unawaited(_toggleMaximized());
              },
              color: cs.onSurface,
            ),
            _TitleBarButton(
              icon: Icons.close,
              onTap: () {
                unawaited(windowManager.destroy());
              },
              color: MWColors.error,
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _toggleMaximized() async {
    if (await windowManager.isMaximized()) {
      await windowManager.unmaximize();
    } else {
      await windowManager.maximize();
    }
  }
}

class _TitleBarButton extends StatelessWidget {
  const _TitleBarButton({
    required this.icon,
    required this.onTap,
    required this.color,
  });

  final IconData icon;
  final VoidCallback onTap;
  final Color color;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: SizedBox(
        width: 40,
        height: 36,
        child: Icon(icon, size: 16, color: color.withAlpha(180)),
      ),
    );
  }
}
