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

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

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

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

class _FlashSaleHeaderState extends State<FlashSaleHeader> {
  late Duration _remaining;
  Timer? _timer;
  bool _didNotify = false;

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

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

  void _notifyCountdownFinished() {
    if (_didNotify) return;
    _didNotify = true;
    widget.onCountdownFinished?.call();
  }

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

  @override
  Widget build(BuildContext context) {
    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),
          Expanded(child: _buildCountdownSection(_remaining)),
          const SizedBox(width: 8),
          if (widget.onViewAll != null)
            GestureDetector(
              onTap: widget.onViewAll,
              child: Text('Xem tất cả', style: TextStyle(color: Colors.blue[700], fontWeight: FontWeight.bold)),
            ),
        ],
      ),
    );
  }

  Widget _buildCountdownSection(Duration duration) {
    final label = (widget.flashSale?.desTime ?? 'Kết thúc trong');
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Flexible(
          child: FittedBox(
            fit: BoxFit.scaleDown,
            alignment: Alignment.centerLeft,
            child: Text(
              label,
              style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w700, color: Colors.black54),
            ),
          ),
        ),
        const SizedBox(width: 4),
        _buildTimeChip(_formatTwoDigits(duration.inHours)),
        const SizedBox(width: 2),
        const Text(':', style: TextStyle(fontWeight: FontWeight.bold)),
        const SizedBox(width: 2),
        _buildTimeChip(_formatTwoDigits(duration.inMinutes.remainder(60))),
        const SizedBox(width: 2),
        const Text(':', style: TextStyle(fontWeight: FontWeight.bold)),
        const SizedBox(width: 2),
        _buildTimeChip(_formatTwoDigits(duration.inSeconds.remainder(60))),
      ],
    );
  }

  Widget _buildTimeChip(String value) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
      decoration: BoxDecoration(color: Colors.black, borderRadius: BorderRadius.circular(6)),
      child: Text(value, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
    );
  }

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