import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

import 'package:monitoring/config.dart';

class PrestasiScreen extends StatefulWidget {
  final String token;
  const PrestasiScreen({super.key, required this.token});

  @override
  State<PrestasiScreen> createState() => _PrestasiScreenState();
}

class _PrestasiScreenState extends State<PrestasiScreen> {
  List<dynamic> data = [];
  bool loading = true;

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

  Future<void> fetchPrestasi() async {
    final url = '${baseUrl}/prestasi'; // Ganti jika pakai emulator

    try {
      final response = await http.get(
        Uri.parse(url),
        headers: {
          'Accept': 'application/json',
          'Authorization': 'Bearer ${widget.token}',
        },
      );

      if (response.statusCode == 200) {
        final res = json.decode(response.body);
        setState(() {
          data = res['data'] ?? [];
          loading = false;
        });
      } else {
        debugPrint(
          'Gagal ambil prestasi: ${response.statusCode} - ${response.body}',
        );
        setState(() => loading = false);
      }
    } catch (e) {
      debugPrint('Error prestasi: $e');
      setState(() => loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Riwayat Prestasi')),
      body:
          loading
              ? const Center(child: CircularProgressIndicator())
              : data.isEmpty
              ? const Center(child: Text('Belum ada data prestasi.'))
              : ListView.builder(
                itemCount: data.length,
                padding: const EdgeInsets.all(12),
                itemBuilder: (context, index) {
                  final item = data[index];
                  return Card(
                    margin: const EdgeInsets.only(bottom: 12),
                    elevation: 3,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Padding(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              const Icon(
                                Icons.emoji_events,
                                color: Colors.amber,
                                size: 28,
                              ),
                              const SizedBox(width: 8),
                              Expanded(
                                child: Text(
                                  item['nama_prestasi'] ?? '-',
                                  style: const TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 8),
                          Text('Jenis: ${item['jenis_prestasi'] ?? '-'}'),
                          Text('Tingkat: ${item['tingkat'] ?? '-'}'),
                          Text('Peringkat: ${item['peringkat'] ?? '-'}'),
                          Text('Tanggal: ${item['tanggal_prestasi'] ?? '-'}'),
                          if (item['deskripsi'] != null &&
                              item['deskripsi'].toString().isNotEmpty)
                            Padding(
                              padding: const EdgeInsets.only(top: 6),
                              child: Text(
                                item['deskripsi'],
                                style: const TextStyle(color: Colors.black54),
                              ),
                            ),
                          const Divider(height: 20),
                          Text('Santri: ${item['santri']?['nama'] ?? '-'}'),
                          Text('Kelas: ${item['kelas']?['nama_kelas'] ?? '-'}'),
                        ],
                      ),
                    ),
                  );
                },
              ),
    );
  }
}
