import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:monitoring/config.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'dart:convert';

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

  @override
  State<AlumniScreen> createState() => _AlumniScreenState();
}

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

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

  Future<void> fetchAlumni() async {
    final url = '$baseUrl/alumni';

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

      if (response.statusCode == 200) {
        final jsonData = json.decode(response.body);
        debugPrint('Data diterima: ${json.encode(jsonData)}');

        if (jsonData != null &&
            jsonData['data'] != null &&
            jsonData['data'] is List) {
          setState(() {
            data = jsonData['data'];
            loading = false;
          });
        } else {
          debugPrint('Format JSON tidak sesuai: $jsonData');
          setState(() => loading = false);
        }
      } else {
        debugPrint('Gagal ambil alumni: ${response.body}');
        setState(() => loading = false);
      }
    } catch (e) {
      debugPrint('Gagal mengambil alumni: $e');
      setState(() => loading = false);
    }
  }

  Future<void> _launchWhatsApp(String number) async {
    final uri = Uri.parse("https://wa.me/$number");
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri, mode: LaunchMode.externalApplication);
    } else {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('Gagal membuka WhatsApp')));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Data Alumni')),
      body: loading
          ? const Center(child: CircularProgressIndicator())
          : data.isEmpty
              ? const Center(child: Text('Tidak ada data alumni.'))
              : ListView.builder(
                  padding: const EdgeInsets.all(12),
                  itemCount: data.length,
                  itemBuilder: (context, index) {
                    final alumni = data[index];
                    return Card(
                      elevation: 3,
                      margin: const EdgeInsets.only(bottom: 12),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Padding(
                        padding: const EdgeInsets.all(16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                const Icon(
                                  Icons.person,
                                  color: Colors.green,
                                ),
                                const SizedBox(width: 8),
                                Expanded(
                                  child: Text(
                                    alumni['nama'] ?? '-',
                                    style: const TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ),
                                Chip(
                                  label: Text(
                                    'Angkatan ${alumni['angkatan'] ?? 'Tidak Diketahui'}',
                                    style: const TextStyle(fontSize: 12),
                                  ),
                                  backgroundColor: Colors.green.shade50,
                                  labelStyle: const TextStyle(
                                    color: Colors.green,
                                  ),
                                ),
                              ],
                            ),
                            const SizedBox(height: 12),
                            Row(
                              children: [
                                const Icon(
                                  Icons.work_outline,
                                  size: 20,
                                  color: Colors.black54,
                                ),
                                const SizedBox(width: 8),
                                Expanded(
                                  child: Text(
                                    alumni['aktivitas_setelah_lulus'] ?? '-',
                                    style: const TextStyle(fontSize: 14),
                                  ),
                                ),
                              ],
                            ),
                            const SizedBox(height: 6),
                            Row(
                              children: [
                                const Icon(
                                  Icons.phone_android,
                                  size: 20,
                                  color: Colors.black54,
                                ),
                                const SizedBox(width: 8),
                                Text(
                                  alumni['kontak'] ?? '-',
                                  style: const TextStyle(fontSize: 14),
                                ),
                                if ((alumni['kontak'] ?? '')
                                    .toString()
                                    .isNotEmpty)
                                  IconButton(
                                    icon: const FaIcon(
                                      FontAwesomeIcons.whatsapp,
                                      color: Colors.green,
                                    ),
                                    tooltip: 'Hubungi di WhatsApp',
                                    onPressed: () {
                                      _launchWhatsApp(
                                        alumni['kontak'].toString(),
                                      );
                                    },
                                  ),
                              ],
                            ),
                            if (alumni['keterangan'] != null &&
                                alumni['keterangan'].toString().isNotEmpty)
                              Padding(
                                padding: const EdgeInsets.only(top: 8),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    const Icon(
                                      Icons.info_outline,
                                      size: 20,
                                      color: Colors.black54,
                                    ),
                                    const SizedBox(width: 8),
                                    Expanded(
                                      child: Text(
                                        alumni['keterangan'],
                                        style: const TextStyle(fontSize: 14),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                          ],
                        ),
                      ),
                    );
                  },
                ),
    );
  }
}
