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

import 'package:monitoring/config.dart';

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

  @override
  State<KesehatanScreen> createState() => _KesehatanScreenState();
}

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

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

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

    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 data kesehatan: ${response.statusCode}');
        setState(() => loading = false);
      }
    } catch (e) {
      debugPrint('Gagal ambil kesehatan: $e');
      setState(() => loading = false);
    }
  }

  Widget _buildCard(Map<String, dynamic> item) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      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.local_hospital, color: Colors.green),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    item['keluhan'] ?? '-',
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            _infoRow('Diagnosis', item['diagnosis']),
            _infoRow('Saran', item['saran']),
            _infoRow('Kelas', item['kelas_nama']),
            _infoRow('Tanggal', _formatDate(item['created_at'])),
          ],
        ),
      ),
    );
  }

  Widget _infoRow(String label, String? value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 90,
            child: Text(
              '$label:',
              style: const TextStyle(fontWeight: FontWeight.bold),
            ),
          ),
          Expanded(
            child: Text(
              value ?? '-',
              style: const TextStyle(color: Colors.black87),
            ),
          ),
        ],
      ),
    );
  }

  String _formatDate(String? datetime) {
    if (datetime == null) return '-';
    final date = DateTime.tryParse(datetime);
    if (date == null) return '-';
    return '${date.day.toString().padLeft(2, '0')}-${date.month.toString().padLeft(2, '0')}-${date.year}';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Catatan Kesehatan')),
      body:
          loading
              ? const Center(child: CircularProgressIndicator())
              : data.isEmpty
              ? const Center(child: Text('Tidak ada catatan kesehatan.'))
              : RefreshIndicator(
                onRefresh: fetchKesehatan,
                child: ListView.builder(
                  physics: const AlwaysScrollableScrollPhysics(),
                  itemCount: data.length,
                  itemBuilder: (context, index) => _buildCard(data[index]),
                ),
              ),
    );
  }
}
