import 'dart:async';

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

import '../integrations/mattermost/mattermost_push_host_integration.dart';
import 'router.dart';

class AltClientApp extends ConsumerWidget {
  final MattermostPushHostIntegration? mattermostHost;

  const AltClientApp({super.key, this.mattermostHost});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final router = ref.watch(appRouterProvider);
    return MaterialApp.router(
      title: 'ALT',
      routerConfig: router,
      builder: (context, child) {
        return _MattermostNotificationOverlay(
          mattermostHost: mattermostHost,
          child: child ?? const SizedBox.shrink(),
        );
      },
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF006C67)),
        useMaterial3: true,
      ),
    );
  }
}

class _MattermostNotificationOverlay extends StatefulWidget {
  final MattermostPushHostIntegration? mattermostHost;
  final Widget child;

  const _MattermostNotificationOverlay({
    required this.mattermostHost,
    required this.child,
  });

  @override
  State<_MattermostNotificationOverlay> createState() =>
      _MattermostNotificationOverlayState();
}

class _MattermostNotificationOverlayState
    extends State<_MattermostNotificationOverlay> {
  StreamSubscription? _notificationSubscription;

  @override
  void initState() {
    super.initState();
    _subscribe(widget.mattermostHost);
  }

  @override
  void didUpdateWidget(_MattermostNotificationOverlay oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.mattermostHost != widget.mattermostHost) {
      _notificationSubscription?.cancel();
      _subscribe(widget.mattermostHost);
    }
  }

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

  void _subscribe(MattermostPushHostIntegration? host) {
    if (host == null) return;
    _notificationSubscription = host.onNotification.listen((data) {
      if (data['type'] != 'message' || !mounted) return;

      final message = data['message'] as String? ?? '';
      final channel = data['channel_name'] as String? ?? '';
      final sender = data['sender_name'] as String? ?? '';
      final content = sender.isNotEmpty
          ? '[$channel] $sender: $message'
          : message;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(content, maxLines: 2, overflow: TextOverflow.ellipsis),
          duration: const Duration(seconds: 4),
          behavior: SnackBarBehavior.floating,
        ),
      );
    });
  }

  @override
  Widget build(BuildContext context) => widget.child;
}
