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

class SwipeToCheckIn extends StatefulWidget {
  final VoidCallback? onCheckIn;
  final VoidCallback? onCheckOut;
  final bool isLoading;
  final String mode; // 'swipe' or 'nfc'
  final bool isCheckedIn;

  const SwipeToCheckIn({
    super.key,
    this.onCheckIn,
    this.onCheckOut,
    this.isLoading = false,
    this.mode = 'swipe',
    this.isCheckedIn = false,
  });

  @override
  State<SwipeToCheckIn> createState() => _SwipeToCheckInState();
}

class _SwipeToCheckInState extends State<SwipeToCheckIn>
    with SingleTickerProviderStateMixin {
  double _dragValue = 0.0;
  final double _handleSize = 48.0;
  bool _isComplete = false;

  @override
  void didUpdateWidget(SwipeToCheckIn oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.isCheckedIn != oldWidget.isCheckedIn) {
      setState(() {
        _isComplete = false;
        _dragValue = 0.0;
      });
    }
  }

  void _onDragUpdate(DragUpdateDetails details, double maxWidth) {
    if (_isComplete || widget.isLoading) return;
    setState(() {
      _dragValue = (_dragValue + details.delta.dx).clamp(
        0.0,
        maxWidth - _handleSize - 8,
      );
    });
  }

  void _onDragEnd(DragEndDetails details, double maxWidth) {
    if (_isComplete || widget.isLoading) return;
    final threshold = (maxWidth - _handleSize - 8) * 0.8;
    if (_dragValue > threshold) {
      setState(() {
        _dragValue = maxWidth - _handleSize - 8;
        _isComplete = true;
      });
      Future.delayed(const Duration(milliseconds: 300), () {
        if (widget.isCheckedIn) {
          widget.onCheckOut?.call();
        } else {
          widget.onCheckIn?.call();
        }
      });
    } else {
      setState(() {
        _dragValue = 0.0;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final baseColor = widget.isCheckedIn
        ? const Color(0xFF10B981)
        : const Color(0xFF0032A0);

    if (widget.mode == 'nfc') {
      return GestureDetector(
        onTap: () {
          if (widget.isLoading) return;
          // Simulate completion for NFC tap
          Future.delayed(const Duration(milliseconds: 300), () {
            if (widget.isCheckedIn) {
              widget.onCheckOut?.call();
            } else {
              widget.onCheckIn?.call();
            }
          });
        },
        child: Container(
          height: 56,
          decoration: BoxDecoration(
            color: baseColor,
            borderRadius: BorderRadius.circular(16),
            boxShadow: [
              BoxShadow(
                color: baseColor.withOpacity(0.4),
                blurRadius: 25,
                offset: const Offset(0, 10),
                spreadRadius: -5,
              ),
            ],
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(LucideIcons.wifi, color: Colors.white),
              const SizedBox(width: 12),
              Text(
                widget.isLoading
                    ? (widget.isCheckedIn
                          ? "Checking out..."
                          : "Checking in...")
                    : (widget.isCheckedIn ? "NFC Check Out" : "NFC Check In"),
                style: const TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 18,
                ),
              ),
            ],
          ),
        ),
      );
    }

    return LayoutBuilder(
      builder: (context, constraints) {
        final maxWidth = constraints.maxWidth;
        final maxDrag = maxWidth - _handleSize - 8;

        // Calculate background color based on drag
        final progress = _dragValue / maxDrag;
        final startColor = widget.isCheckedIn
            ? const Color(0xFF10B981)
            : const Color(0xFF0032A0);
        final endColor = widget.isCheckedIn
            ? const Color(0xFF0032A0)
            : const Color(0xFF10B981);
        final currentColor =
            Color.lerp(startColor, endColor, progress) ?? startColor;

        return Container(
          height: 56,
          decoration: BoxDecoration(
            color: currentColor,
            borderRadius: BorderRadius.circular(16),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 4,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Stack(
            children: [
              Center(
                child: Opacity(
                  opacity: 1.0 - progress,
                  child: Text(
                    widget.isCheckedIn
                        ? "Swipe to Check Out"
                        : "Swipe to Check In",
                    style: TextStyle(
                      color: Colors.white.withOpacity(0.8),
                      fontWeight: FontWeight.w600,
                      fontSize: 18,
                    ),
                  ),
                ),
              ),
              if (_isComplete)
                Center(
                  child: Text(
                    widget.isCheckedIn ? "Check Out!" : "Check In!",
                    style: const TextStyle(
                      color: Colors.white,
                      fontWeight: FontWeight.w600,
                      fontSize: 18,
                    ),
                  ),
                ),
              Positioned(
                left: 4 + _dragValue,
                top: 4,
                child: GestureDetector(
                  onHorizontalDragUpdate: (d) => _onDragUpdate(d, maxWidth),
                  onHorizontalDragEnd: (d) => _onDragEnd(d, maxWidth),
                  child: Container(
                    width: _handleSize,
                    height: _handleSize,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(12),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.1),
                          blurRadius: 2,
                          offset: const Offset(0, 1),
                        ),
                      ],
                    ),
                    child: Center(
                      child: Icon(
                        _isComplete
                            ? LucideIcons.check
                            : LucideIcons.arrowRight,
                        color: startColor,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
