import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../core/theme/halo_tokens.dart';
import '../../../core/theme/widgets/widgets.dart';
import '../providers/support_handles_provider.dart';

/// Phase 4 Stage 8 — Tanya Admin sheet.
///
/// Reads handles from `supportHandlesProvider` (CC-config-driven) and surfaces
/// WA + Telegram deeplinks. Tap → `url_launcher` external app. No webview.
class TanyaAdminSheet extends ConsumerWidget {
  const TanyaAdminSheet({super.key});

  static Future<void> show(BuildContext context) {
    return HaloBottomSheet.show<void>(
      context,
      child: const TanyaAdminSheet(),
    );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final handlesAsync = ref.watch(supportHandlesProvider);

    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        const Text(
          'tanya admin',
          textAlign: TextAlign.center,
          style: TextStyle(
            fontFamily: HaloTokens.fontDisplay,
            fontSize: 22,
            fontWeight: FontWeight.w700,
            color: HaloTokens.ink,
          ),
        ),
        const SizedBox(height: HaloSpacing.s8),
        const Text(
          'pilih cara yang paling enak buat kamu — admin bakal balas secepatnya.',
          textAlign: TextAlign.center,
          style: TextStyle(
            fontFamily: HaloTokens.fontBody,
            fontSize: 14,
            color: HaloTokens.inkSoft,
          ),
        ),
        const SizedBox(height: HaloSpacing.s24),
        handlesAsync.when(
          loading: () => const Padding(
            padding: EdgeInsets.symmetric(vertical: HaloSpacing.s24),
            child: Center(child: CircularProgressIndicator()),
          ),
          error: (_, __) => Padding(
            padding: const EdgeInsets.symmetric(vertical: HaloSpacing.s16),
            child: Column(
              children: [
                const Text(
                  'gagal mengambil kontak admin. coba lagi sebentar.',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    fontFamily: HaloTokens.fontBody,
                    fontSize: 13,
                    color: HaloTokens.danger,
                  ),
                ),
                const SizedBox(height: HaloSpacing.s12),
                HaloButton(
                  label: 'coba lagi',
                  variant: HaloButtonVariant.secondary,
                  fullWidth: true,
                  onPressed: () => ref.invalidate(supportHandlesProvider),
                ),
              ],
            ),
          ),
          data: (handles) => Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              if (handles.wa != null)
                HaloButton(
                  label: handles.wa!.label.isEmpty ? 'WhatsApp' : handles.wa!.label,
                  variant: HaloButtonVariant.primary,
                  fullWidth: true,
                  icon: const Icon(Icons.chat_bubble_outline),
                  onPressed: () => _launch(context, handles.wa!.deeplink),
                ),
              if (handles.wa != null && handles.telegram != null)
                const SizedBox(height: HaloSpacing.s12),
              if (handles.telegram != null)
                HaloButton(
                  label: handles.telegram!.label.isEmpty
                      ? 'Telegram'
                      : handles.telegram!.label,
                  variant: HaloButtonVariant.secondary,
                  fullWidth: true,
                  icon: const Icon(Icons.send_outlined),
                  onPressed: () => _launch(context, handles.telegram!.deeplink),
                ),
              if (handles.wa == null && handles.telegram == null)
                const Padding(
                  padding: EdgeInsets.symmetric(vertical: HaloSpacing.s16),
                  child: Text(
                    'kontak admin belum tersedia. coba lagi nanti ya.',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontFamily: HaloTokens.fontBody,
                      fontSize: 13,
                      color: HaloTokens.inkSoft,
                    ),
                  ),
                ),
            ],
          ),
        ),
      ],
    );
  }

  Future<void> _launch(BuildContext context, String deeplink) async {
    final uri = Uri.tryParse(deeplink);
    if (uri == null) return;
    final ok = await launchUrl(uri, mode: LaunchMode.externalApplication);
    if (!ok && context.mounted) {
      // Fall back to platform default if external launch refused.
      await launchUrl(uri);
    }
  }
}
