import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:lgcc/models/item_model.dart';
import 'package:lgcc/providers/wordpress_service.dart';
import 'package:lgcc/pages/detail_item.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';

class ItemsList extends StatelessWidget {
  final dynamic itemDetail;
  final String type;

  const ItemsList({Key? key, required this.type, this.itemDetail})
    : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(type),
        centerTitle: true,
        backgroundColor: Color(0xFFE5EBFD),
      ),
      body: _buildItemListView(context),
    );
  }

  Widget _buildItemListView(BuildContext context) {
    final WordpressService wordpressService = WordpressService();
    return FutureBuilder<List<dynamic>>(
      future: wordpressService.fetchItems(type),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        } else if (snapshot.hasError) {
          return Center(child: Text('Error: ${snapshot.error}'));
        } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
          return const Center(child: Text('No hay items disponibles.'));
        } else {
          final List<ItemModel> items = snapshot.data!.cast<ItemModel>();

          return ListView.builder(
            itemCount: items.length,
            itemBuilder: (context, index) {
              final item = items[index];
              return ListTile(
                title: Text(item.title),
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => DetailItem(items: item),
                    ),
                  );
                },
              );
            },
          );
        }
      },
    );
  }
}
