import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

// Static variable to prevent refresh spamming
bool _isRefreshInProgress = false;

class EmptyStateWidget extends StatelessWidget {
  final VoidCallback onTap;

  const EmptyStateWidget({super.key, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _guardedOnTap,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 120,
              height: 120,
              decoration: BoxDecoration(
                color: Colors.green.withOpacity(0.1),
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.chat_bubble_outline,
                size: 60,
                color: Colors.green.shade700,
              ),
            ),
            const SizedBox(height: 24),
            Text(
              'Belum ada pesan',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
                color: Colors.grey[800],
              ),
            ),
            const SizedBox(height: 8),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 32),
              child: Text(
                'Mulai percakapan dengan komunitas petani lainnya',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 16, color: Colors.grey[600]),
              ),
            ),
            const SizedBox(height: 24),
            ElevatedButton(
              // Use guarded refresh function to avoid multiple refreshes
              onPressed: _guardedOnTap,
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF00A884),
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(
                  horizontal: 24,
                  vertical: 12,
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(24),
                ),
              ),
              child: const Text(
                'Refresh',
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // Prevents multiple refreshes from happening at the same time
  void _guardedOnTap() {
    if (_isRefreshInProgress) {
      print('[INFO] Refresh already in progress, ignoring tap');
      return;
    }

    _isRefreshInProgress = true;
    print('[FORCE] EmptyState Refresh button pressed with cooldown');

    // Call the onTap callback just once
    onTap();

    // Only do one delayed call with reasonable timeout
    Future.delayed(Duration(seconds: 5), () {
      _isRefreshInProgress = false;
      print('[INFO] Refresh cooldown complete, ready for next refresh');
    });
  }
}
