import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'dart:js' as js;

class WhatsAppButton extends StatefulWidget {
  final String phoneNumber;
  final double size;

  const WhatsAppButton({
    super.key,
    required this.phoneNumber,
    this.size = 24,
  });

  @override
  State<WhatsAppButton> createState() => _WhatsAppButtonState();
}

class _WhatsAppButtonState extends State<WhatsAppButton> {
  bool _isPressed = false;

  void _openWhatsApp() {
    if (kIsWeb) {
      // Use JavaScript for web/PWA - this actually works
      try {
        final urls = [
          'whatsapp://send?phone=${widget.phoneNumber}',
          'https://wa.me/${widget.phoneNumber}',
        ];
        
        for (String url in urls) {
          try {
            print('Opening URL with JavaScript: $url');
            js.context.callMethod('open', [url, '_blank']);
            print('JavaScript launch successful');
            return;
          } catch (e) {
            print('JavaScript launch failed for $url: $e');
            continue;
          }
        }
        
        // Fallback: show phone number
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('Contact via WhatsApp: ${widget.phoneNumber}'),
              backgroundColor: Colors.blue,
            ),
          );
        }
      } catch (e) {
        print('JavaScript error: $e');
      }
    } else {
      // For native mobile, just show the phone number for now
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Contact via WhatsApp: ${widget.phoneNumber}'),
            backgroundColor: Colors.blue,
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: _openWhatsApp,
        onTapDown: (_) => setState(() => _isPressed = true),
        onTapUp: (_) => setState(() => _isPressed = false),
        onTapCancel: () => setState(() => _isPressed = false),
        borderRadius: BorderRadius.circular((widget.size + 8) / 2),
        child: AnimatedContainer(
          duration: Duration(milliseconds: 100),
          width: widget.size + 8,
          height: widget.size + 8,
          decoration: BoxDecoration(
            color: _isPressed ? Color(0xFF1DA851) : Color(0xFF25D366),
            borderRadius: BorderRadius.circular((widget.size + 8) / 2),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.2),
                blurRadius: 4,
                offset: Offset(0, 2),
              ),
            ],
          ),
          child: Icon(
            Icons.message,
            color: Colors.white,
            size: widget.size * 0.6,
          ),
        ),
      ),
    );
  }
}