import 'package:flutter/material.dart';
import 'package:tugas_akhir_supabase/screens/community/components/guide_card.dart';
import 'package:tugas_akhir_supabase/screens/community/components/guide_detail_dialog.dart';
import 'package:tugas_akhir_supabase/screens/community/models/farming_guide_model.dart';
import 'package:tugas_akhir_supabase/screens/community/services/guide_service.dart';

class GuidesListView extends StatefulWidget {
  final String categoryFilter;

  const GuidesListView({super.key, this.categoryFilter = ''});

  @override
  State<GuidesListView> createState() => _GuidesListViewState();
}

class _GuidesListViewState extends State<GuidesListView> {
  late Future<List<FarmingGuideModel>> _guidesFuture;
  final _guideService = GuideService();
  bool _hasError = false;
  String _errorMessage = '';

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

  @override
  void didUpdateWidget(GuidesListView oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.categoryFilter != widget.categoryFilter) {
      _loadGuides();
    }
  }

  void _loadGuides() {
    setState(() {
      _hasError = false;
      _errorMessage = '';

      if (widget.categoryFilter.isEmpty) {
        _guidesFuture = _guideService.getGuides();
      } else {
        _guidesFuture = _guideService.getGuidesByCategory(
          widget.categoryFilter,
        );
      }
    });
  }

  void _showGuideDetail(BuildContext context, FarmingGuideModel guide) {
    GuideDetailDialog.show(context, guide);
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<FarmingGuideModel>>(
      future: _guidesFuture,
      builder: (context, snapshot) {
        // Menampilkan loading indicator
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }

        // Menangani error
        if (snapshot.hasError || _hasError) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.error_outline, size: 48, color: Colors.red[300]),
                const SizedBox(height: 16),
                Text(
                  _hasError ? _errorMessage : 'Gagal memuat data panduan',
                  style: TextStyle(color: Colors.red[700]),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 16),
                ElevatedButton.icon(
                  onPressed: _loadGuides,
                  icon: const Icon(Icons.refresh),
                  label: const Text('Coba Lagi'),
                ),
              ],
            ),
          );
        }

        // Menangani data kosong
        if (!snapshot.hasData || snapshot.data!.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.menu_book, size: 48, color: Colors.grey[400]),
                const SizedBox(height: 16),
                Text(
                  widget.categoryFilter.isEmpty
                      ? 'Belum ada panduan tersedia'
                      : 'Belum ada panduan untuk kategori ${widget.categoryFilter}',
                  style: TextStyle(fontSize: 16, color: Colors.grey[600]),
                  textAlign: TextAlign.center,
                ),
              ],
            ),
          );
        }

        // Menampilkan daftar panduan
        final guides = snapshot.data!;
        return RefreshIndicator(
          onRefresh: () async {
            _loadGuides();
            return Future.delayed(const Duration(milliseconds: 500));
          },
          child: ListView.builder(
            padding: const EdgeInsets.all(16),
            physics: const AlwaysScrollableScrollPhysics(),
            itemCount: guides.length,
            itemBuilder: (context, index) {
              final guide = guides[index];
              return GuideCard(
                guide: guide,
                onTap: () => _showGuideDetail(context, guide),
              );
            },
          ),
        );
      },
    );
  }
}
