import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../shared/widgets/custom_toast_message.dart';

class RechargeSheet extends StatelessWidget {
  final String code;
  const RechargeSheet({super.key, required this.code});
  String _buildUssd(String prefix) => '$prefix*$code#';

  Future<void> _dialUssd(String ussd) async {
    final uri = Uri(scheme: 'tel', path: ussd.replaceAll('#', Uri.encodeComponent('#')));
    debugPrint('Dialing USSD: $uri');
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    }
  }

  @override
  Widget build(BuildContext context) {
    final pre = _buildUssd('*100');
    final post = _buildUssd('*199');
    return SafeArea(
      top: false,
      child: Padding(
        padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
        child: Column(
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const Spacer(),
                const Expanded(
                  flex: 6,
                  child: Text(
                    'Nạp ngay',
                    textAlign: TextAlign.center, // ✅ căn giữa
                    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 22),
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.close),
                  onPressed: () => Navigator.of(context).pop(),
                )
              ],
            ),
            const SizedBox(height: 4),
            _RechargeTile(title: 'Cú pháp nạp thẻ trả trước', subtitle: pre, onTap: () => _dialUssd(pre)),
            const Divider(height: 1),
            _RechargeTile(title: 'Cú pháp nạp thẻ trả sau', subtitle: post, onTap: () => _dialUssd(post)),
            const SizedBox(height: 8),
          ],
        ),
      ),
    );
  }
}

class _RechargeTile extends StatelessWidget {
  final String title;
  final String subtitle;
  final VoidCallback onTap;

  const _RechargeTile({required this.title, required this.subtitle, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return ListTile(
      contentPadding: EdgeInsets.zero,
      title: Text(title, style: const TextStyle(fontWeight: FontWeight.w600)),
      subtitle: Text(subtitle, style: const TextStyle(color: Colors.black54)),
      trailing: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          GestureDetector(
              onTap: () {
                Clipboard.setData(ClipboardData(text: subtitle));
                showToastMessage('Đã sao chép');
              },
              child: Icon(Icons.copy)
          ),
          SizedBox(width: 12),
          const Icon(Icons.chevron_right),
        ],
      ),
      onTap: onTap,
    );
  }
}
