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

import '../services/web_socket_service.dart';

class ConnectionStatusBanner extends StatelessWidget {
  const ConnectionStatusBanner({super.key});

  @override
  Widget build(BuildContext context) {
    final webSocketService = context.read<WebSocketService>();

    return StreamBuilder<SocketConnectionStatus>(
      stream: webSocketService.connectionState,
      initialData: webSocketService.connectionStatus,
      builder: (context, snapshot) {
        final connectionStatus =
            snapshot.data ?? SocketConnectionStatus.disconnected;
        final isVisible = connectionStatus != SocketConnectionStatus.connected;
        final isConnecting =
            connectionStatus == SocketConnectionStatus.connecting;

        return AnimatedContainer(
          duration: const Duration(milliseconds: 250),
          curve: Curves.easeInOut,
          height: isVisible ? 52 : 0,
          color:
              isConnecting ? Colors.amber.shade700 : Colors.redAccent.shade700,
          child: isVisible
              ? SafeArea(
                  bottom: false,
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 10,
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            isConnecting
                                ? '正在重连...(第${webSocketService.retryCount.clamp(1, 999)}次)'
                                : '连接断开',
                            style: Theme.of(context)
                                .textTheme
                                .bodyMedium
                                ?.copyWith(
                                  color: Colors.black,
                                  fontWeight: FontWeight.w600,
                                ),
                          ),
                        ),
                        if (!isConnecting)
                          TextButton(
                            onPressed: () {
                              webSocketService.manualReconnect();
                            },
                            style: TextButton.styleFrom(
                              foregroundColor: Colors.white,
                              backgroundColor: Colors.black26,
                              padding: const EdgeInsets.symmetric(
                                horizontal: 12,
                                vertical: 8,
                              ),
                            ),
                            child: const Text('重试'),
                          ),
                      ],
                    ),
                  ),
                )
              : null,
        );
      },
    );
  }
}
