import 'dart:async';
import 'package:flutter/material.dart';
import '../theme/app_colors.dart';
import '../theme/app_text_styles.dart';
import '../theme/app_radius.dart';
import '../theme/app_gradients.dart';
import '../utils/formatters.dart';

class RateLimitTimer extends StatefulWidget {
  final int totalSeconds;
  final VoidCallback? onComplete;

  const RateLimitTimer({super.key, required this.totalSeconds, this.onComplete});

  @override
  State<RateLimitTimer> createState() => _RateLimitTimerState();
}

class _RateLimitTimerState extends State<RateLimitTimer> {
  late int _remaining;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _remaining = widget.totalSeconds;
    _timer = Timer.periodic(const Duration(seconds: 1), (_) {
      if (_remaining <= 1) {
        _timer?.cancel();
        setState(() => _remaining = 0);
        widget.onComplete?.call();
      } else {
        setState(() => _remaining--);
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    final isDone = _remaining <= 0;

    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: AppGradients.rateLimitBg,
        border: Border.all(color: AppColors.warning.withOpacity(0.25)),
        borderRadius: AppRadius.lgAll,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            '⏳ Rate Limit Reached',
            style: AppTextStyles.titleSmall.copyWith(color: AppColors.warning),
          ),
          const SizedBox(height: 4),
          if (isDone)
            Text(
              '✅ You can chat again now!',
              style: AppTextStyles.titleMedium.copyWith(color: AppColors.success),
            )
          else ...[
            Text(
              'API cooldown — you can chat again in:',
              style: AppTextStyles.bodySmall,
            ),
            const SizedBox(height: 8),
            Text(
              Formatters.countdown(_remaining),
              style: AppTextStyles.displayMedium.copyWith(
                fontWeight: FontWeight.w900,
                fontFeatures: [const FontFeature.tabularFigures()],
              ),
            ),
          ],
        ],
      ),
    );
  }
}