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

/// Diagnostic app to test MediaKit installation and video loading
/// 
/// Run this to diagnose black screen issues:
/// flutter run -t lib/diagnostic_main.dart
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Test MediaKit before initializing the app
  debugPrint('========================================');
  debugPrint('SPLASH VIDEO DIAGNOSTIC TEST');
  debugPrint('========================================');
  
  // Initialize and run the app
  SplashVideo.initialize();

  final mediaKitWorking = await SplashVideo.testMediaKit();
  
  if (!mediaKitWorking) {
    debugPrint('');
    debugPrint('⚠️  MediaKit is not working correctly!');
    debugPrint('');
    debugPrint('Solutions:');
    debugPrint('1. Make sure these dependencies are in pubspec.yaml:');
    debugPrint('   - media_kit: ^1.2.6');
    debugPrint('   - media_kit_video: ^2.0.1');
    debugPrint('   - media_kit_libs_android_video: any  (for Android)');
    debugPrint('   - media_kit_libs_ios_video: any      (for iOS)');
    debugPrint('   - media_kit_libs_macos_video: any    (for macOS)');
    debugPrint('   - media_kit_libs_windows_video: any  (for Windows)');
    debugPrint('   - media_kit_libs_linux: any          (for Linux)');
    debugPrint('');
    debugPrint('2. Run: flutter pub get');
    debugPrint('3. Run: flutter clean && flutter pub get');
    debugPrint('4. Restart your IDE/editor');
    debugPrint('========================================');
  } else {
    debugPrint('');
    debugPrint('✅ MediaKit is working!');
    debugPrint('========================================');
  }
  
  runApp(const DiagnosticApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SplashVideo Diagnostic',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
        useMaterial3: true,
      ),
      home: const DiagnosticPage(),
    );
  }
}

class DiagnosticPage extends StatefulWidget {
  const DiagnosticPage({super.key});

  @override
  State<DiagnosticPage> createState() => _DiagnosticPageState();
}

class _DiagnosticPageState extends State<DiagnosticPage> {
  String? errorMessage;
  bool videoLoaded = false;
  Duration? videoDuration;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          // The splash video
          SplashVideo(
            source: AssetSource('assets/splash.mp4'),
            backgroundColor: Colors.black,
            onVideoError: (error) {
              debugPrint('❌ Video error callback: $error');
              setState(() {
                errorMessage = error;
              });
            },
            videoConfig: VideoConfig(
              playImmediately: true,
              scale: VideoScaleMode.cover,
              onPlayerInitialized: (player) {
                debugPrint('🎬 Player initialized callback');
                setState(() {
                  videoLoaded = true;
                });
              },
            ),
            // Navigate after 5 seconds for testing
            nextScreen: const DiagnosticResult(),
          ),
          
          // Status overlay
          Positioned(
            top: 50,
            left: 20,
            right: 20,
            child: Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.black.withValues(alpha: 0.7),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Text(
                    'DIAGNOSTIC MODE',
                    style: TextStyle(
                      color: Colors.yellow,
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),
                  const SizedBox(height: 8),
                  _buildStatusRow('Video Asset', 'assets/splash.mp4'),
                  _buildStatusRow(
                    'Video Loaded',
                    videoLoaded ? '✅ Yes' : '⏳ Loading...',
                  ),
                  if (videoDuration != null)
                    _buildStatusRow('Duration', videoDuration.toString()),
                  if (errorMessage != null) ...[
                    const SizedBox(height: 8),
                    Text(
                      'ERROR: $errorMessage',
                      style: const TextStyle(
                        color: Colors.red,
                        fontSize: 12,
                      ),
                    ),
                  ],
                ],
              ),
            ),
          ),
          
          // Check console message
          if (!videoLoaded && errorMessage == null)
            Positioned(
              bottom: 50,
              left: 20,
              right: 20,
              child: Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.blue.withValues(alpha: 0.8),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: const Text(
                  '💡 Check the console/logs for detailed diagnostic information',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildStatusRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        children: [
          Text(
            '$label: ',
            style: const TextStyle(
              color: Colors.white70,
              fontSize: 12,
            ),
          ),
          Text(
            value,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 12,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.green,
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.check_circle,
              size: 100,
              color: Colors.white,
            ),
            const SizedBox(height: 20),
            const Text(
              'SUCCESS!',
              style: TextStyle(
                fontSize: 32,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            const SizedBox(height: 10),
            const Text(
              'Video played successfully',
              style: TextStyle(
                fontSize: 18,
                color: Colors.white70,
              ),
            ),
            const SizedBox(height: 40),
            ElevatedButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('Back to Diagnostic'),
            ),
          ],
        ),
      ),
    );
  }
}
