import 'package:flutter/material.dart';

enum SnackBarType { warning, success, error }

class CustomSnackBar {
  static bool _isVisible = false;

  static void show(
    BuildContext context,
    String message,
    SnackBarType type, {
    Duration duration = const Duration(seconds: 3),
  }) {
    if (_isVisible) return;
    _isVisible = true;

    OverlayState overlayState = Overlay.of(context);
    late OverlayEntry overlayEntry;

    Color backgroundColor;
    IconData icon;

    switch (type) {
      case SnackBarType.success:
        backgroundColor = Colors.green;
        icon = Icons.check_circle;
        break;
      case SnackBarType.error:
        backgroundColor = Colors.red;
        icon = Icons.error;
        break;
      case SnackBarType.warning:
      default:
        backgroundColor = Colors.orange;
        icon = Icons.warning;
        break;
    }

    final controller = AnimationController(
      vsync: Navigator.of(context),
      duration: Duration(milliseconds: 500),
    );

    final animation = Tween<Offset>(
      begin: Offset(1.5, 0.0),
      end: Offset(0.0, 0.0),
    ).animate(CurvedAnimation(
      parent: controller,
      curve: Curves.easeOut,
    ));

    overlayEntry = OverlayEntry(
      builder: (context) => Positioned(
        top: 50,
        left: 10,
        right: 10,
        child: SlideTransition(
          position: animation,
          child: Material(
            color: Colors.transparent,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              decoration: BoxDecoration(
                color: backgroundColor.withAlpha(240),
                borderRadius: BorderRadius.circular(15),
              ),
              child: Row(
                children: [
                  Icon(icon, color: Colors.white),
                  SizedBox(width: 10),
                  Expanded(
                    child: Text(
                      message,
                      style: TextStyle(color: Colors.white, fontSize: 14),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      controller.reverse().then((_) {
                        if (overlayEntry.mounted) {
                          overlayEntry.remove();
                        }
                        _isVisible = false;
                      });
                    },
                    child: Icon(Icons.close, color: Colors.white),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );

    overlayState.insert(overlayEntry);
    controller.forward();

    Future.delayed(duration, () {
      if (overlayEntry.mounted) {
        controller.reverse().then((_) {
          overlayEntry.remove();
          _isVisible = false;
        });
      }
    });
  }
}
