import 'package:core_localization/core_localization.dart';
import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';

class SwipeToCheckIn extends StatefulWidget {
  const SwipeToCheckIn({
    super.key,
    this.onCheckIn,
    this.onCheckOut,
    this.isLoading = false,
    this.mode = 'swipe',
    this.isCheckedIn = false,
  });
  final VoidCallback? onCheckIn;
  final VoidCallback? onCheckOut;
  final bool isLoading;
  final String mode; // 'swipe' or 'nfc'
  final bool isCheckedIn;

  @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 double 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 i18n = Translations.of(context).staff.clock_in.swipe;
    final Color baseColor = widget.isCheckedIn
        ? UiColors.success
        : UiColors.primary;

    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: UiConstants.radiusLg,
            boxShadow: <BoxShadow>[
              BoxShadow(
                color: baseColor.withValues(alpha: 0.4),
                blurRadius: 25,
                offset: const Offset(0, 10),
                spreadRadius: -5,
              ),
            ],
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Icon(UiIcons.wifi, color: UiColors.white),
              const SizedBox(width: UiConstants.space3),
              Text(
                widget.isLoading
                    ? (widget.isCheckedIn
                          ? i18n.checking_out
                          : i18n.checking_in)
                    : (widget.isCheckedIn ? i18n.nfc_checkout : i18n.nfc_checkin),
                style: UiTypography.body1b.white,
              ),
            ],
          ),
        ),
      );
    }

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

        // Calculate background color based on drag
        final double progress = _dragValue / maxDrag;
        final Color startColor = widget.isCheckedIn
            ? UiColors.success
            : UiColors.primary;
        final Color endColor = widget.isCheckedIn
            ? UiColors.primary
            : UiColors.success;
        final Color currentColor =
            Color.lerp(startColor, endColor, progress) ?? startColor;

        return Container(
          height: 56,
          decoration: BoxDecoration(
            color: currentColor,
            borderRadius: UiConstants.radiusLg,
            boxShadow: <BoxShadow>[
              BoxShadow(
                color: UiColors.black.withValues(alpha: 0.1),
                blurRadius: 4,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: Stack(
            children: <Widget>[
              Center(
                child: Opacity(
                  opacity: 1.0 - progress,
                  child: Text(
                    widget.isCheckedIn
                        ? i18n.swipe_checkout
                        : i18n.swipe_checkin,
                    style: UiTypography.body1b,
                  ),
                ),
              ),
              if (_isComplete)
                Center(
                  child: Text(
                    widget.isCheckedIn ? i18n.checkout_complete : i18n.checkin_complete,
                    style: UiTypography.body1b,
                  ),
                ),
              Positioned(
                left: 4 + _dragValue,
                top: 4,
                child: GestureDetector(
                  onHorizontalDragUpdate: (DragUpdateDetails d) =>
                      _onDragUpdate(d, maxWidth),
                  onHorizontalDragEnd: (DragEndDetails d) =>
                      _onDragEnd(d, maxWidth),
                  child: Container(
                    width: _handleSize,
                    height: _handleSize,
                    decoration: BoxDecoration(
                      color: UiColors.white,
                      borderRadius: UiConstants.radiusLg,
                      boxShadow: <BoxShadow>[
                        BoxShadow(
                          color: UiColors.black.withValues(alpha: 0.1),
                          blurRadius: 2,
                          offset: const Offset(0, 1),
                        ),
                      ],
                    ),
                    child: Center(
                      child: Icon(
                        _isComplete ? UiIcons.check : UiIcons.arrowRight,
                        color: startColor,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
