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

import '../blocs/connection/connection_bloc.dart';
import '../blocs/connection/connection_event.dart';
import '../blocs/connection/connection_state.dart' as conn;

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

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<ConnectionBloc, conn.ConnectionState>(
      builder: (context, state) {
        Color backgroundColor;
        Color textColor;
        String statusText;
        IconData statusIcon;

        switch (state.overallStatus) {
          case conn.ConnectionOverallStatus.connected:
            backgroundColor = Colors.green.shade100;
            textColor = Colors.green.shade800;
            statusText = 'Connected (${state.connectedCount}/${state.totalCount})';
            statusIcon = Icons.cloud_done;
          case conn.ConnectionOverallStatus.partial:
            backgroundColor = Colors.orange.shade100;
            textColor = Colors.orange.shade800;
            statusText = 'Partial (${state.connectedCount}/${state.totalCount})';
            statusIcon = Icons.cloud_off;
          case conn.ConnectionOverallStatus.connecting:
            backgroundColor = Colors.blue.shade100;
            textColor = Colors.blue.shade800;
            statusText = 'Connecting...';
            statusIcon = Icons.cloud_sync;
          case conn.ConnectionOverallStatus.disconnected:
            backgroundColor = Colors.red.shade100;
            textColor = Colors.red.shade800;
            statusText = 'Disconnected';
            statusIcon = Icons.cloud_off;
        }

        return Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          decoration: BoxDecoration(
            color: backgroundColor,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(statusIcon, color: textColor, size: 18),
              const SizedBox(width: 8),
              Text(
                statusText,
                style: TextStyle(
                  color: textColor,
                  fontWeight: FontWeight.w500,
                ),
              ),
              if (state.overallStatus == conn.ConnectionOverallStatus.disconnected ||
                  state.overallStatus == conn.ConnectionOverallStatus.partial) ...[
                const SizedBox(width: 8),
                InkWell(
                  onTap: () => context
                      .read<ConnectionBloc>()
                      .add(const RetryConnections()),
                  child: Icon(Icons.refresh, color: textColor, size: 18),
                ),
              ],
            ],
          ),
        );
      },
    );
  }
}
