import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../cubit/inspection_topology_state.dart';

class NetworkTopologyWidget extends StatelessWidget {
  final List<TopologyNode> topologyNodes;
  final int deviceCount;
  final int connectionCount;
  final Function(TopologyNode) onNodeTap;

  const NetworkTopologyWidget({
    super.key,
    required this.topologyNodes,
    required this.deviceCount,
    required this.connectionCount,
    required this.onNodeTap,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 32.h),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(24.r),
          bottomRight: Radius.circular(24.r),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '网络拓扑',
                style: TextStyle(
                  fontSize: 28.sp,
                  fontWeight: FontWeight.w600,
                  color: const Color.fromRGBO(15, 23, 42, 1),
                ),
              ),
              Text(
                '共$deviceCount个设备,$connectionCount条连接',
                style: TextStyle(
                  fontSize: 24.sp,
                  color: const Color.fromRGBO(148, 163, 184, 1),
                ),
              ),
            ],
          ),
          SizedBox(height: 32.h),
          SizedBox(
            width: double.infinity,
            height: 800.h,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(32.r),
              child: Stack(
                children: [
                  Container(
                    width: double.infinity,
                    height: double.infinity,
                    color: const Color.fromRGBO(241, 245, 249, 1),
                  ),
                  if (topologyNodes.isNotEmpty)
                    CustomPaint(
                      size: Size.infinite,
                      painter: TopologyPainter(nodes: topologyNodes),
                    ),
                  if (topologyNodes.isNotEmpty)
                    LayoutBuilder(
                      builder: (context, constraints) {
                        final List<Widget> clickableNodes = [];
                        _collectNodes(
                          topologyNodes[0],
                          clickableNodes,
                          constraints.maxWidth,
                          constraints.maxHeight,
                        );
                        return Stack(children: clickableNodes);
                      },
                    ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _collectNodes(
    TopologyNode node,
    List<Widget> nodes,
    double maxWidth,
    double maxHeight,
  ) {
    final centerX = maxWidth * node.x;
    final centerY = maxHeight * node.y;
    final nodeWidth = 150.w;
    // final nodeHeight = node.name.length > 4 ? 160.h : 100.h;
    final nodeHeight = 80.h;

    nodes.add(
      Positioned(
        left: centerX - nodeWidth / 2,
        top: centerY - nodeHeight / 2,
        width: nodeWidth,
        height: nodeHeight,
        child: GestureDetector(
          onTap: () => onNodeTap(node),
          child: Container(
            decoration: BoxDecoration(
              color: const Color.fromRGBO(239, 246, 255, 1),
              border: Border.all(
                color: const Color.fromRGBO(59, 130, 246, 1),
                width: 1.w,
              ),
              borderRadius: BorderRadius.circular(60.r),
            ),
            child: Center(
              child: Text(
                node.name,
                style: TextStyle(
                  color: const Color.fromRGBO(71, 85, 105, 1),
                  fontSize: 24.sp,
                  fontWeight: FontWeight.w500,
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        ),
      ),
    );

    for (var child in node.children) {
      _collectNodes(child, nodes, maxWidth, maxHeight);
    }
  }
}

class TopologyPainter extends CustomPainter {
  final List<TopologyNode> nodes;

  TopologyPainter({required this.nodes});

  @override
  void paint(Canvas canvas, Size size) {
    if (nodes.isEmpty) return;

    final paint = Paint()
      ..color = const Color.fromRGBO(203, 213, 225, 1)
      ..strokeWidth = 3.w
      ..style = PaintingStyle.stroke;

    _drawConnections(canvas, size, nodes[0], paint);
  }

  void _drawConnections(Canvas canvas, Size size, TopologyNode node, Paint paint) {
    final centerX = size.width * node.x;
    final centerY = size.height * node.y;

    for (var child in node.children) {
      final childCenterX = size.width * child.x;
      final childCenterY = size.height * child.y;

      canvas.drawLine(
        Offset(centerX, centerY),
        Offset(childCenterX, childCenterY),
        paint,
      );

      _drawConnections(canvas, size, child, paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
