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

/// A widget that handles the OTP resend logic and countdown timer.
class OtpResendSection extends StatefulWidget {
  /// Callback for when the resend link is pressed.
  final VoidCallback onResend;

  /// Whether an error is currently displayed. (Used for layout tweaks in the original code)
  final bool hasError;

  /// Creates an [OtpResendSection].
  const OtpResendSection({
    super.key,
    required this.onResend,
    this.hasError = false,
  });

  @override
  State<OtpResendSection> createState() => _OtpResendSectionState();
}

class _OtpResendSectionState extends State<OtpResendSection> {
  int _countdown = 30;

  @override
  void initState() {
    super.initState();
    _startCountdown();
  }

  /// Starts the countdown timer.
  void _startCountdown() {
    Future.delayed(const Duration(seconds: 1), () {
      if (mounted && _countdown > 0) {
        setState(() => _countdown--);
        _startCountdown();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text.rich(
        TextSpan(
          children: <InlineSpan>[
            TextSpan(
              text: widget.hasError
                  ? ''
                  : '${t.staff_authentication.otp_verification.did_not_get_code}  ',
              style: UiTypography.body2r.textSecondary,
            ),
            WidgetSpan(
              child: GestureDetector(
                onTap: _countdown > 0 ? null : widget.onResend,
                child: Text(
                  _countdown > 0
                      ? t.staff_authentication.otp_verification.resend_in(
                          seconds: _countdown.toString(),
                        )
                      : t.staff_authentication.otp_verification.resend_code,
                  style: (_countdown > 0
                      ? UiTypography.body2r.textSecondary
                      : UiTypography.body2b.textPrimary),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
