import 'package:flutter/material.dart';
import 'package:be_happy/di/service_locator.dart';
import '../../core/app_colors.dart';
import '../components/custom_app_bar.dart';
import '../components/content_parser.dart';
import '../../domain/usecase/get_news_by_id_usecase.dart';

class NewsDetailScreen extends StatefulWidget {
  final int newsId;
  final String title;

  const NewsDetailScreen({
    super.key,
    required this.newsId,
    required this.title,
  });

  @override
  State<NewsDetailScreen> createState() => _NewsDetailScreenState();
}

class _NewsDetailScreenState extends State<NewsDetailScreen> {
  bool _isLoading = true;
  String? _errorMessage;
  dynamic _news;

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

  Future<void> _fetchNews() async {
    try {
      final usecase = getIt<GetNewsByIdUsecase>();
      final news = await usecase(widget.newsId);

      if (mounted) {
        setState(() {
          _news = news;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = e.toString();
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(gradient: AppColors.phoneScreenBg),
        child: SafeArea(
          child: Column(
            children: [
              const SizedBox(height: 16),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: CustomAppBar(title: widget.title),
              ),

              // 🔹 Контент
              Expanded(
                child: _isLoading
                    ? const Center(
                  child: CircularProgressIndicator(color: Colors.white),
                )
                    : _errorMessage != null
                    ? Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Text(
                        'Ошибка загрузки новости',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      const SizedBox(height: 16),
                      Text(
                        _errorMessage!,
                        style: TextStyle(
                          color: Colors.white.withOpacity(0.6),
                          fontSize: 14,
                        ),
                        textAlign: TextAlign.center,
                      ),
                      const SizedBox(height: 24),
                      ElevatedButton(
                        onPressed: () {
                          setState(() {
                            _isLoading = true;
                            _errorMessage = null;
                            _fetchNews();
                          });
                        },
                        child: const Text('Повторить'),
                      ),
                    ],
                  ),
                )
                    : _news != null
                    ? _buildNewsContent(_news)
                    : const SizedBox.shrink(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildNewsContent(dynamic news) {
    return SingleChildScrollView(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // ✅ Используем вынесенный парсер
          ...ContentParser.parseContent(
            textJson: news.textJson,
            text: news.text,
          ),
        ],
      ),
    );
  }

  // 🔹 Удалены старые методы: _parseHtmlText, _parseHtmlElements, _parseJsonText, _parseJsonNode

  String _formatDate(DateTime? date) {
    if (date == null) return '';
    final localDate = date.toLocal();
    return '${localDate.day.toString().padLeft(2, '0')}.${localDate.month.toString().padLeft(2, '0')}.${localDate.year}';
  }
}