// lib/screens/features/pelanggaran_screen.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class PelanggaranScreen extends StatefulWidget {
  final String token;

  const PelanggaranScreen({super.key, required this.token});

  @override
  State<PelanggaranScreen> createState() => _PelanggaranScreenState();
}

class _PelanggaranScreenState extends State<PelanggaranScreen> {
  List<dynamic> _pelanggaranList = [];
  bool _loading = true;

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

  Future<void> fetchPelanggaran() async {
    try {
      final response = await http.get(
        Uri.parse("http://10.75.50.24:8000/api/pelanggaran"),
        headers: {
          "Authorization": "Bearer ${widget.token}",
          "Accept": "application/json",
        },
      );

      final data = jsonDecode(response.body);
      if (data["success"] == true) {
        setState(() {
          _pelanggaranList = data["data"];
          _loading = false;
        });
      } else {
        throw Exception("Gagal mengambil data");
      }
    } catch (e) {
      setState(() {
        _loading = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text("Error: $e")),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Data Pelanggaran"),
        backgroundColor: const Color(0xFF43A047),
      ),
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : _pelanggaranList.isEmpty
              ? const Center(child: Text("Tidak ada data pelanggaran."))
              : ListView.builder(
                  itemCount: _pelanggaranList.length,
                  itemBuilder: (context, index) {
                    final item = _pelanggaranList[index];
                    return Card(
                      margin:
                          const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                      child: ListTile(
                        // title: Text(item["nama_santri"] ?? "-"),
                        subtitle: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text("Kelas: ${item["nama_kelas"] ?? '-'}"),
                            Text("Jenis: ${item["jenis_pelanggaran"] ?? '-'}"),
                            Text("Hukuman: ${item["hukuman"] ?? '-'}"),
                            Text("Guru Penegur: ${item["nama_penginput"] ?? '-'}"),
                          ],
                        ),
                        // trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                      ),
                    );
                  },
                ),
    );
  }
}