import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:neomovies_mobile/data/models/player/video_source.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class WebPlayerWidget extends StatefulWidget {
  final String mediaId;
  final String mediaType;
  final VideoSource source;
  final String? title;
  final String? subtitle;
  final String? posterUrl;

  const WebPlayerWidget({
    Key? key,
    required this.mediaId,
    required this.mediaType,
    required this.source,
    this.title,
    this.subtitle,
    this.posterUrl,
  }) : super(key: key);

  @override
  State<WebPlayerWidget> createState() => _WebPlayerWidgetState();
}

class _WebPlayerWidgetState extends State<WebPlayerWidget> {
  late WebViewController _controller;
  bool _isLoading = true;
  String? _error;
  String? _playerUrl;

  @override
  void initState() {
    super.initState();
    _initializeWebView();
  }

  void _initializeWebView() {
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.black)
      ..setUserAgent('Mozilla/5.0 (Linux; Android 10; SM-G975F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.120 Mobile Safari/537.36')
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (String url) {
            print('WebView started loading: $url');
            if (mounted) {
              setState(() {
                _isLoading = true;
                _error = null;
              });
            }
          },
          onPageFinished: (String url) {
            print('WebView finished loading: $url');
            if (mounted) {
              setState(() {
                _isLoading = false;
              });
            }
          },
          onWebResourceError: (WebResourceError error) {
            print('WebView error: ${error.description}');
            if (mounted) {
              setState(() {
                _isLoading = false;
                _error = 'Ошибка загрузки: ${error.description}';
              });
            }
          },
          onHttpError: (HttpResponseError error) {
            print('WebView HTTP error: ${error.response?.statusCode}');
            if (mounted) {
              setState(() {
                _isLoading = false;
                _error = 'HTTP ошибка: ${error.response?.statusCode}';
              });
            }
          },
        ),
      );

    _loadPlayer();
  }

  Future<void> _loadPlayer() async {
    try {
      setState(() {
        _isLoading = true;
        _error = null;
      });

      final baseUrl = dotenv.env['API_URL'];
      final apiUrl = '$baseUrl/players/${widget.source.name}?imdb_id=${widget.mediaId}';
      
      print('Fetching player data from: $apiUrl');
      
      // Делаем запрос к API для получения данных плеера
      final response = await http.get(
        Uri.parse(apiUrl),
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'User-Agent': 'Mozilla/5.0 (Linux; Android 10; SM-G975F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.120 Mobile Safari/537.36',
        },
      );

      if (response.statusCode != 200) {
        throw Exception('HTTP ${response.statusCode}: ${response.reasonPhrase}');
      }

      final responseBody = response.body;
      print('API Response: $responseBody');

      String? playerUrl;

      // Пытаемся парсить JSON
      try {
        final jsonData = json.decode(responseBody);
        if (jsonData is Map<String, dynamic>) {
          // Ищем URL в разных полях
          playerUrl = jsonData['iframe'] ?? 
                     jsonData['src'] ?? 
                     jsonData['url'] ??
                     jsonData['link'];
        }
      } catch (e) {
        print('Failed to parse JSON, trying to extract iframe from HTML: $e');
      }

      // Если JSON не сработал, пытаемся найти iframe в HTML
      if (playerUrl == null && responseBody.isNotEmpty) {
        final iframeMatch = RegExp(r'<iframe[^>]*src="([^"]+)"', caseSensitive: false)
            .firstMatch(responseBody);
        if (iframeMatch != null) {
          playerUrl = iframeMatch.group(1);
        }
      }

      // Если все еще не нашли URL, возможно весь response и есть URL
      if (playerUrl == null && responseBody.isNotEmpty) {
        // Проверяем, является ли ответ просто URL
        final urlPattern = RegExp(r'^https?://[^\s]+$');
        if (urlPattern.hasMatch(responseBody.trim())) {
          playerUrl = responseBody.trim();
        }
      }

      if (playerUrl == null || playerUrl.isEmpty) {
        throw Exception('Не удалось найти URL плеера в ответе API');
      }

      print('Loading player URL: $playerUrl');
      
      setState(() {
        _playerUrl = playerUrl;
      });

      // Загружаем URL напрямую в WebView
      await _controller.loadRequest(Uri.parse(playerUrl));
      
    } catch (e) {
      print('Error loading player: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
          _error = 'Ошибка загрузки плеера: $e';
        });
      }
    }
  }

  @override
  void didUpdateWidget(WebPlayerWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    
    // Reload player if source or media changed
    if (oldWidget.source != widget.source || 
        oldWidget.mediaId != widget.mediaId ||
        oldWidget.mediaType != widget.mediaType) {
      print('Widget updated, reloading player...');
      _loadPlayer();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.black,
      child: Stack(
        children: [
          // WebView отображается всегда, когда есть URL
          if (_playerUrl != null)
            WebViewWidget(controller: _controller),
          
          // Индикатор загрузки поверх WebView
          if (_isLoading)
            Container(
              color: Colors.black54,
              child: const Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CircularProgressIndicator(color: Colors.white),
                    SizedBox(height: 16),
                    Text(
                      'Загрузка плеера...',
                      style: TextStyle(color: Colors.white),
                    ),
                  ],
                ),
              ),
            ),
          
          // Показываем ошибку только если нет URL
          if (_error != null && _playerUrl == null)
            Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(
                    Icons.error_outline,
                    color: Colors.red,
                    size: 48,
                  ),
                  const SizedBox(height: 16),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: Text(
                      _error!,
                      style: const TextStyle(color: Colors.white),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () {
                      _loadPlayer();
                    },
                    child: const Text('Повторить'),
                  ),
                  const SizedBox(height: 8),
                  // Debug info
                  if (widget.mediaId.isNotEmpty)
                    Container(
                      padding: const EdgeInsets.all(8),
                      margin: const EdgeInsets.symmetric(horizontal: 16),
                      decoration: BoxDecoration(
                        color: Colors.grey.shade800,
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Column(
                        children: [
                          Text(
                            'Debug Info:',
                            style: TextStyle(
                              color: Colors.grey.shade300,
                              fontSize: 12,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            'IMDB ID: ${widget.mediaId}',
                            style: TextStyle(
                              color: Colors.grey.shade300,
                              fontSize: 10,
                              fontFamily: 'monospace',
                            ),
                          ),
                          Text(
                            'Source: ${widget.source.name}',
                            style: TextStyle(
                              color: Colors.grey.shade300,
                              fontSize: 10,
                              fontFamily: 'monospace',
                            ),
                          ),
                          Text(
                            'API URL: ${dotenv.env['API_URL']}/players/${widget.source.name}?imdb_id=${widget.mediaId}',
                            style: TextStyle(
                              color: Colors.grey.shade300,
                              fontSize: 10,
                              fontFamily: 'monospace',
                            ),
                            textAlign: TextAlign.center,
                          ),
                        ],
                      ),
                    ),
                ],
              ),
            ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}