import 'package:flutter/material.dart';

import '../../../core/infra/player_engine/player_engine.dart';
import '../services/frame_jank_monitor.dart';


const int _kLowBufferLeadMs = 1000;


class PlayerDebugHud extends StatelessWidget {
  const PlayerDebugHud({
    super.key,
    required this.engine,
    required this.frameMonitor,
  });

  final PlayerEngine engine;
  final FrameJankMonitor frameMonitor;

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.topLeft,
      child: Padding(
        padding: const EdgeInsets.only(top: 56, left: 12),
        child: IgnorePointer(
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
            decoration: BoxDecoration(
              color: Colors.black.withValues(alpha: 0.62),
              borderRadius: BorderRadius.circular(8),
            ),
            child: DefaultTextStyle(
              style: const TextStyle(
                color: Colors.white,
                fontSize: 12,
                height: 1.5,
                fontFamily: 'monospace',
                fontFamilyFallback: ['Consolas', 'Menlo', 'monospace'],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Text(
                    'DEBUG',
                    style: TextStyle(
                      color: Colors.lightGreenAccent,
                      fontSize: 11,
                      fontWeight: FontWeight.bold,
                      letterSpacing: 1.5,
                    ),
                  ),
                  Text('engine: ${engine.displayName}'),
                  ValueListenableBuilder<PlaybackStats?>(
                    valueListenable: engine.debugStats,
                    builder: (context, stats, _) => _StatsBlock(stats: stats),
                  ),
                  ValueListenableBuilder<FrameDiag>(
                    valueListenable: frameMonitor.diag,
                    builder: (context, diag, _) => _FrameBlock(diag: diag),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class _StatsBlock extends StatelessWidget {
  const _StatsBlock({required this.stats});

  final PlaybackStats? stats;

  @override
  Widget build(BuildContext context) {
    final s = stats;
    if (s == null) {
      return const Text('engine: (no stats yet)');
    }
    final low = s.bufferLeadMs < _kLowBufferLeadMs;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        Text('decoder: ${s.decoder}  (hwdec=${s.hwdec})'),
        Text('isDV: ${s.isDolbyVision}   rate: ${s.rate}x'),
        Text('bitrate: ${s.bitrateMbps.toStringAsFixed(1)} Mbps'),
        Text(
          'bufferLead: ${s.bufferLeadMs} ms',
          style: TextStyle(
            color: low ? Colors.orangeAccent : Colors.white,
            fontWeight: low ? FontWeight.bold : FontWeight.normal,
          ),
        ),
      ],
    );
  }
}

class _FrameBlock extends StatelessWidget {
  const _FrameBlock({required this.diag});

  final FrameDiag diag;

  @override
  Widget build(BuildContext context) {
    final rasterHot = diag.lastRasterMs >= 32;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: [
        const SizedBox(height: 4),
        Text('fps: ${diag.fps.toStringAsFixed(0)}'),
        Text(
          'raster: ${diag.lastRasterMs.toStringAsFixed(1)} ms',
          style: TextStyle(
            color: rasterHot ? Colors.orangeAccent : Colors.white,
            fontWeight: rasterHot ? FontWeight.bold : FontWeight.normal,
          ),
        ),
        Text('build: ${diag.lastBuildMs.toStringAsFixed(1)} ms'),
        Text('jank frames: ${diag.jankCount}'),
      ],
    );
  }
}
