import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../shared/router_gage.dart';
import '../../shared/widgets/custom_empty_widget.dart';
import '../../shared/widgets/custom_navigation_bar.dart';
import 'news_item_widget.dart';
import 'news_list_viewmodel.dart';

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

  @override
  _NewsListScreenState createState() => _NewsListScreenState();
}

class _NewsListScreenState extends State<NewsListScreen> {
  late final NewsListViewModel _viewModel = Get.put(NewsListViewModel());

  @override
  void initState() {
    super.initState();
    _viewModel.getNewsList(isRefresh: true);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      appBar: CustomNavigationBar(title: "MyPoint có gì hot?"),
      body: Column(
        children: [
          Expanded(
            child: Obx(() {
              if (_viewModel.newsList.isEmpty) {
                return Center(child: EmptyWidget(isLoading: _viewModel.isLoading.value));
              }
              return RefreshIndicator(
                onRefresh: () => _viewModel.getNewsList(isRefresh: true),
                child: ListView.builder(
                  physics: const AlwaysScrollableScrollPhysics(),
                  itemCount: _viewModel.newsList.length + (_viewModel.canLoadMore ? 1 : 0),
                  itemBuilder: (context, index) {
                    if (index >= _viewModel.newsList.length && _viewModel.newsList.isNotEmpty) {
                      WidgetsBinding.instance.addPostFrameCallback((_) {
                        if (!_viewModel.isLoading.value) {
                          _viewModel.getNewsList(isRefresh: false);
                        }
                      });
                      return const Center(
                        child: Padding(
                          padding: EdgeInsets.all(16),
                          child: CircularProgressIndicator(),
                        ),
                      );
                    }
                    final news = _viewModel.newsList.value[index];
                    return GestureDetector(
                      onTap: () {
                        Get.toNamed(campaignDetailScreen, arguments: {"id": news.pageId ?? ""});
                      },
                      child: PageItemWidget(item: news),
                    );
                  },
                ),
              );
            }),
          ),
          const SizedBox(height: 16),
        ],
      ),
    );
  }
}
