import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:window_manager/window_manager.dart';
import '../services/image_manager.dart';
import '../services/file_handler.dart';

class AppShortcuts extends StatelessWidget {
  final Widget child;

  const AppShortcuts({super.key, required this.child});

  @override
  Widget build(BuildContext context) {
    return Focus(
      autofocus: true,
      onKeyEvent: (node, event) {
        if (event is KeyDownEvent) {
          final ctrl = HardwareKeyboard.instance.isControlPressed;
          final shift = HardwareKeyboard.instance.isShiftPressed;

          // Ctrl+Shift+Q: tüm pencereleri kapat
          if (ctrl && shift && event.logicalKey == LogicalKeyboardKey.keyQ) {
            if (Platform.isWindows) {
              Process.runSync('taskkill', ['/F', '/IM', 'imajviewer.exe']);
            } else {
              Process.runSync('pkill', ['imajviewer']);
            }
            return KeyEventResult.handled;
          }

          switch (event.logicalKey) {
            case LogicalKeyboardKey.arrowLeft:
              ImageManager.instance.previousImage();
              return KeyEventResult.handled;
            case LogicalKeyboardKey.arrowRight:
              ImageManager.instance.nextImage();
              return KeyEventResult.handled;
            case LogicalKeyboardKey.escape:
              windowManager.isFullScreen().then((isFullscreen) {
                if (isFullscreen) windowManager.setFullScreen(false);
              });
              return KeyEventResult.handled;
          }
        }
        return KeyEventResult.ignored;
      },
      child: CallbackShortcuts(
        bindings: {
          const SingleActivator(
            LogicalKeyboardKey.keyO,
            control: true,
          ): () {
            FileHandler.openFileDialog();
          },
          const SingleActivator(LogicalKeyboardKey.f11): () async {
            final isFullscreen = await windowManager.isFullScreen();
            await windowManager.setFullScreen(!isFullscreen);
          },
          const SingleActivator(
            LogicalKeyboardKey.keyQ,
            control: true,
          ): () {
            windowManager.close();
          },
        },
        child: child,
      ),
    );
  }
}
