import 'dart:async';
import 'package:flutter/material.dart';
import '../../flash_sale/preview_flash_sale_model.dart';

class FlashSaleHeader extends StatefulWidget {
  final PreviewFlashSale? flashSale;
  final VoidCallback? onViewAll;

  const FlashSaleHeader({
    super.key,
    required this.flashSale,
    this.onViewAll,
  });

  @override
  State<FlashSaleHeader> createState() => _FlashSaleHeaderState();
}

class _FlashSaleHeaderState extends State<FlashSaleHeader> {
  late Duration _remaining;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _remaining = widget.flashSale?.countdownLocal ?? Duration(seconds: 100000);
    _startTimer();
  }

  void _startTimer() {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (_) {
      if (_remaining.inSeconds <= 0) {
        _timer?.cancel();
      } else {
        setState(() {
          _remaining -= const Duration(seconds: 1);
        });
      }
    });
  }

  String _formatTime(int value) => value.toString().padLeft(2, '0');

  Widget _buildTimeBox(String text) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 3, vertical: 2),
      decoration: BoxDecoration(
        color: Colors.red.shade400,
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        text,
        style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
      ),
    );
  }

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

  @override
  Widget build(BuildContext context) {
    final hours = _formatTime(_remaining.inHours);
    final minutes = _formatTime(_remaining.inMinutes.remainder(60));
    final seconds = _formatTime(_remaining.inSeconds.remainder(60));

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      child: Row(
        children: [
          Image.asset("assets/images/ic_flash_sale.png", height: 24, fit: BoxFit.cover,),
          const SizedBox(width: 6),
          Text(widget.flashSale?.desTime ?? "", style: TextStyle(fontSize: 14)),
          const SizedBox(width: 4),
          _buildTimeBox(hours),
          const SizedBox(width: 2),
          const Text(":", style: TextStyle(fontWeight: FontWeight.bold)),
          const SizedBox(width: 2),
          _buildTimeBox(minutes),
          const SizedBox(width: 2),
          const Text(":", style: TextStyle(fontWeight: FontWeight.bold)),
          const SizedBox(width: 2),
          _buildTimeBox(seconds),
          const Spacer(),
          if (widget.onViewAll != null)
            GestureDetector(
              onTap: widget.onViewAll,
              child: Text(
                'Xem tất cả',
                style: TextStyle(color: Colors.blue[700], fontWeight: FontWeight.bold),
              ),
            ),
        ],
      ),
    );
  }
}
