import 'dart:io';

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


class TopDragArea extends StatefulWidget {
  final Widget child;
  final double topResizeZone;


  final bool enabled;

  const TopDragArea({
    super.key,
    required this.child,
    this.topResizeZone = 6,
    this.enabled = true,
  });

  @override
  State<TopDragArea> createState() => _TopDragAreaState();
}

class _TopDragAreaState extends State<TopDragArea> with WindowListener {
  bool _isMaximized = false;

  bool get _supported =>
      widget.enabled && (Platform.isMacOS || Platform.isWindows);

  @override
  void initState() {
    super.initState();
    if (_supported) {
      windowManager.addListener(this);
      _syncMaximized();
    }
  }

  @override
  void dispose() {
    if (Platform.isMacOS || Platform.isWindows) {
      windowManager.removeListener(this);
    }
    super.dispose();
  }

  Future<void> _syncMaximized() async {
    try {
      final maximized = await windowManager.isMaximized();
      if (!mounted) return;
      if (maximized != _isMaximized) {
        setState(() => _isMaximized = maximized);
      }
    } catch (_) {}
  }

  @override
  void onWindowMaximize() {
    if (mounted) setState(() => _isMaximized = true);
  }

  @override
  void onWindowUnmaximize() {
    if (mounted) setState(() => _isMaximized = false);
  }

  @override
  Widget build(BuildContext context) {
    if (!_supported) return widget.child;
    final showResizeZone =
        Platform.isWindows && !_isMaximized && widget.topResizeZone > 0;
    final deadZone = showResizeZone ? widget.topResizeZone : 0.0;

    return Stack(
      children: [
        Padding(
          padding: EdgeInsets.only(top: deadZone),
          child: DragToMoveArea(child: widget.child),
        ),
        if (showResizeZone)
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            height: deadZone,
            child: MouseRegion(
              cursor: SystemMouseCursors.resizeUp,
              child: GestureDetector(
                behavior: HitTestBehavior.opaque,
                onPanStart: (_) => windowManager.startResizing(ResizeEdge.top),
              ),
            ),
          ),
      ],
    );
  }
}
