import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/widgets/image_loader.dart';

class HoverView extends StatefulWidget {
  final String imagePath;
  final VoidCallback? onTap;
  final VoidCallback? onClose;
  final double size;
  final Color backgroundColor;
  final Color closeButtonColor;
  final double countDownTime;

  const HoverView({
    super.key,
    required this.imagePath,
    this.onTap,
    this.onClose,
    this.size = 100.0,
    this.backgroundColor = Colors.white,
    this.closeButtonColor = Colors.red,
    this.countDownTime = 0.0,
  });

  @override
  State<HoverView> createState() => _HoverViewState();
}

class _HoverViewState extends State<HoverView> {
  Offset _position = const Offset(0, 0);
  bool _isDragging = false;
  bool _showCloseButton = false;
  Size _screenSize = Size.zero;
  bool _isInitialized = false;
  final _remainingSeconds = 0.obs;
  Timer? _timer;
  double get _expandBottom {
    if (_remainingSeconds.value > 0) {
      return 30.0;
    }
    return 8.0;
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _setInitialPosition();
    });
    _remainingSeconds.value = widget.countDownTime.toInt();
    _startTimer();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  void _startTimer() {
    _timer?.cancel();
    if (_remainingSeconds.value > 0) {
      _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        if (!mounted) return;
        setState(() {
          _remainingSeconds.value--;
          print("Remaining seconds: ${_remainingSeconds.value}");
          if (_remainingSeconds.value <= 0) _timer?.cancel();
        });
      });
    }
  }

  void _setInitialPosition() {
    if (!mounted) return;
    final paddingBottom = MediaQuery.of(context).padding.bottom + _expandBottom;
    final size = MediaQuery.of(context).size;
    if (size.width > 0 && size.height > 0) {
      setState(() {
        _screenSize = size;
        _position = Offset(_screenSize.width - widget.size - 20, _screenSize.height - widget.size - paddingBottom);
        _isInitialized = true;
      });
    }
  }

  void _onPanStart(DragStartDetails details) {
    setState(() {
      _isDragging = true;
      _showCloseButton = true;
    });
  }

  String _formatTime(int seconds) {
    if (seconds > 30 * 3600) {
      final days = (seconds / 86400).ceil();
      return '$days Ngày';
    } else {
      final h = (seconds ~/ 3600).toString().padLeft(2, '0');
      final m = ((seconds % 3600) ~/ 60).toString().padLeft(2, '0');
      final s = (seconds % 60).toString().padLeft(2, '0');
      return '$h:$m:$s';
    }
  }

  void _onPanUpdate(DragUpdateDetails details) {
    if (!mounted || _screenSize.width <= 0 || _screenSize.height <= 0) return;
    setState(() {
      _position += details.delta;
      // Constrain position within screen bounds
      _position = Offset(
        _position.dx.clamp(0, _screenSize.width - widget.size),
        _position.dy.clamp(0, _screenSize.height - widget.size),
      );
    });
  }

  void _onPanEnd(DragEndDetails details) {
    setState(() {
      _isDragging = false;
    });
    _snapToNearestCorner();
  }

  void _snapToNearestCorner() {
    final paddingBottom = MediaQuery.of(context).padding.bottom + _expandBottom;
    if (!mounted || _screenSize.width <= 0 || _screenSize.height <= 0) return;
    final corners = [
      Offset(20, paddingBottom), // Top left
      Offset(_screenSize.width - widget.size - 20, paddingBottom), // Top right
      Offset(20, _screenSize.height - widget.size - paddingBottom), // Bottom left
      Offset(_screenSize.width - widget.size - 20, _screenSize.height - widget.size - paddingBottom), // Bottom right
    ];

    Offset nearestCorner = corners[0];
    double minDistance = double.infinity;

    for (final corner in corners) {
      final distance = (_position - corner).distance;
      if (distance < minDistance) {
        minDistance = distance;
        nearestCorner = corner;
      }
    }

    // Animate to nearest corner using setState
    setState(() {
      _position = nearestCorner;
      _showCloseButton = false;
    });
  }

  void _onTap() {
    if (widget.onTap != null) {
      widget.onTap!();
    }
  }

  void _onClose() {
    if (widget.onClose != null) {
      widget.onClose!();
    }
  }

  @override
  Widget build(BuildContext context) {
    // Update screen size on build to handle orientation changes
    final currentSize = MediaQuery.of(context).size;
    if (_screenSize != currentSize && currentSize.width > 0 && currentSize.height > 0) {
      _screenSize = currentSize;

      // Adjust position if needed when screen size changes
      if (_isInitialized) {
        _position = Offset(
          _position.dx.clamp(0, _screenSize.width - widget.size),
          _position.dy.clamp(0, _screenSize.height - widget.size),
        );
      } else {
        _setInitialPosition();
      }
    }
    // Don't render until we have valid dimensions
    if (!_isInitialized || _screenSize.width <= 0 || _screenSize.height <= 0) {
      return const SizedBox.shrink();
    }

    return Positioned(
      left: _position.dx,
      top: _position.dy,
      width: widget.size,
      height: widget.size + (_remainingSeconds.value > 0 ? 26 : 0),
      child: GestureDetector(
        onPanStart: _onPanStart,
        onPanUpdate: _onPanUpdate,
        onPanEnd: _onPanEnd,
        onTap: _onTap,
        onLongPress: () {
          setState(() {
            _showCloseButton = !_showCloseButton;
          });
        },
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            // Main container with image (no border, no pulse effect)
            Column(
              children: [
                AnimatedScale(
                  scale: _isDragging ? 1.1 : 1.0,
                  duration: const Duration(milliseconds: 200),
                  child: SizedBox(
                    width: widget.size,
                    height: widget.size,
                    child:
                        widget.imagePath.startsWith('http')
                            ? loadNetworkImage(url: widget.imagePath, placeholderAsset: 'assets/images/ic_pipi_05.png')
                            : Image.asset(widget.imagePath, fit: BoxFit.cover),
                  ),
                ),
                Obx(()
                  => (_remainingSeconds.value > 0)
                          ? Container(
                            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                            decoration: BoxDecoration(
                              color: Colors.black.withOpacity(0.6),
                              borderRadius: BorderRadius.circular(18),
                            ),
                            child: Text(
                              _formatTime(_remainingSeconds.value),
                              style: const TextStyle(fontSize: 12, color: Colors.white, fontWeight: FontWeight.w600),
                            ),
                          )
                          : SizedBox.shrink(),
                ),
              ],
            ),
            // Close button
            if (_showCloseButton)
              Positioned(
                top: -8,
                right: -8,
                width: 24,
                height: 24,
                child: GestureDetector(
                  onTap: _onClose,
                  child: const Icon(Icons.close, color: Colors.transparent, size: 16),
                ),
              ),
          ],
        ),
      ),
    );
  }
}
