import 'package:flutter/material.dart';

import '../../../domain/entities/wall_config.dart';
import '../../blocs/wall/wall_state.dart';
import 'viewer_tile.dart';

/// A physical monitor that can contain 1-4 viewers (quad view)
class PhysicalMonitorTile extends StatelessWidget {
  final PhysicalMonitor monitor;
  final WallState wallState;
  final Function(int viewerId) onViewerTap;

  const PhysicalMonitorTile({
    super.key,
    required this.monitor,
    required this.wallState,
    required this.onViewerTap,
  });

  @override
  Widget build(BuildContext context) {
    final isSelected = wallState.isPhysicalMonitorSelected(monitor);
    final hasAlarm = _hasAnyAlarm();

    return Container(
      decoration: BoxDecoration(
        border: isSelected
            ? Border.all(color: const Color(0xFF00D4FF), width: 3)
            : Border.all(color: const Color(0xFF4A5568), width: 1),
        borderRadius: BorderRadius.circular(6),
        color: hasAlarm
            ? const Color(0xFFDC2626).withValues(alpha: 0.3)
            : Colors.transparent,
      ),
      child: Padding(
        padding: const EdgeInsets.all(2),
        child: monitor.hasMultipleViewers
            ? _buildQuadView(context)
            : _buildSingleView(context),
      ),
    );
  }

  bool _hasAnyAlarm() {
    for (final viewerId in monitor.viewerIds) {
      if (wallState.getViewerState(viewerId).hasAlarm) {
        return true;
      }
    }
    return false;
  }

  Widget _buildSingleView(BuildContext context) {
    final viewerId = monitor.primaryViewerId;
    final viewerState = wallState.getViewerState(viewerId);
    final isViewerSelected = wallState.isViewerSelected(viewerId);

    return AspectRatio(
      aspectRatio: 16 / 9,
      child: ViewerTile(
        viewerId: viewerId,
        viewerState: viewerState,
        isSelected: isViewerSelected,
        onTap: () => onViewerTap(viewerId),
      ),
    );
  }

  Widget _buildQuadView(BuildContext context) {
    // Arrange viewers in 2x2 grid
    return AspectRatio(
      aspectRatio: 16 / 9,
      child: GridView.count(
        crossAxisCount: 2,
        mainAxisSpacing: 2,
        crossAxisSpacing: 2,
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        children: monitor.viewerIds.map((viewerId) {
          final viewerState = wallState.getViewerState(viewerId);
          final isViewerSelected = wallState.isViewerSelected(viewerId);

          return ViewerTile(
            viewerId: viewerId,
            viewerState: viewerState,
            isSelected: isViewerSelected,
            isPartOfQuad: true,
            onTap: () => onViewerTap(viewerId),
          );
        }).toList(),
      ),
    );
  }
}
