part of '../../app/app.dart';

class ExaminationListScreen extends StatefulWidget {
  const ExaminationListScreen({
    super.key,
    required this.token,
    required this.baseUrl,
    required this.master,
    required this.title,
  });

  final String token;
  final String baseUrl;
  final String master;
  final String title;

  @override
  State<ExaminationListScreen> createState() => _ExaminationListScreenState();
}

class _ExaminationListScreenState extends State<ExaminationListScreen> {
  late final ApiClient _api;
  late Future<Map<String, dynamic>> _future;
  final _search = TextEditingController();

  @override
  void initState() {
    super.initState();
    _api = ApiClient(baseUrl: widget.baseUrl, token: widget.token);
    _future = _load();
  }

  @override
  void dispose() {
    _search.dispose();
    super.dispose();
  }

  Future<Map<String, dynamic>> _load() {
    final query = _search.text.trim();
    return _api.get(
      'api/mobile/books/${widget.master}/examinations',
      query.isEmpty ? null : {'search': query},
    );
  }

  void _reload() {
    setState(() {
      _future = _load();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: [
          IconButton(
            onPressed: _reload,
            icon: const Icon(Icons.refresh),
            tooltip: 'Refresh',
          ),
        ],
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 8, 16, 10),
            child: TextField(
              controller: _search,
              textInputAction: TextInputAction.search,
              onSubmitted: (_) => _reload(),
              decoration: InputDecoration(
                prefixIcon: const Icon(Icons.search),
                labelText: 'Cari no lab, RM, pasien, order',
                border: const OutlineInputBorder(),
                suffixIcon: IconButton(
                  onPressed: _reload,
                  icon: const Icon(Icons.arrow_forward),
                  tooltip: 'Cari',
                ),
              ),
            ),
          ),
          Expanded(
            child: FutureBuilder<Map<String, dynamic>>(
              future: _future,
              builder: (context, snapshot) {
                if (snapshot.connectionState != ConnectionState.done) {
                  return const LoadingScreen();
                }
                if (snapshot.hasError) {
                  return ErrorView(
                    message: _message(snapshot.error),
                    onRetry: _reload,
                  );
                }
                final items = asList(snapshot.data!['items']);
                if (items.isEmpty) {
                  return const EmptyPanel(text: 'Tidak ada pemeriksaan aktif.');
                }
                return RefreshIndicator(
                  onRefresh: () async => _reload(),
                  child: ListView.builder(
                    padding: const EdgeInsets.fromLTRB(16, 0, 16, 24),
                    itemCount: items.length,
                    itemBuilder: (context, index) => ExaminationCard(
                      item: asMap(items[index]),
                      token: widget.token,
                      baseUrl: widget.baseUrl,
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

class ExaminationCompactTile extends StatelessWidget {
  const ExaminationCompactTile({
    super.key,
    required this.item,
    required this.token,
    required this.baseUrl,
  });

  final Map<String, dynamic> item;
  final String token;
  final String baseUrl;

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(
        item['nmpasien']?.toString() ?? '-',
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
      ),
      subtitle: Text(
        '${item['nofoto'] ?? '-'} - ${item['warning_label'] ?? item['status'] ?? '-'}',
      ),
      trailing: const Icon(Icons.chevron_right),
      onTap: () => _openDetail(context, item, token, baseUrl),
    );
  }
}

class ExaminationCard extends StatelessWidget {
  const ExaminationCard({
    super.key,
    required this.item,
    required this.token,
    required this.baseUrl,
  });

  final Map<String, dynamic> item;
  final String token;
  final String baseUrl;

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.only(bottom: 10),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      child: InkWell(
        borderRadius: BorderRadius.circular(8),
        onTap: () => _openDetail(context, item, token, baseUrl),
        child: Padding(
          padding: const EdgeInsets.all(14),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Expanded(
                    child: Text(
                      item['nmpasien']?.toString() ?? '-',
                      style: const TextStyle(fontWeight: FontWeight.w800),
                    ),
                  ),
                  StatusPill(status: item['status']?.toString() ?? 'NEW'),
                ],
              ),
              const SizedBox(height: 8),
              Text(
                '${item['nofoto'] ?? '-'} / RM ${item['noregister'] ?? '-'}',
              ),
              Text(
                item['reques']?.toString() ?? '-',
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              const SizedBox(height: 10),
              Row(
                children: [
                  const Icon(Icons.schedule, size: 16, color: Colors.black54),
                  const SizedBox(width: 6),
                  Expanded(
                    child: Text(
                      item['daftar']?.toString() ?? '-',
                      style: const TextStyle(color: Colors.black54),
                    ),
                  ),
                  TextButton.icon(
                    onPressed: () => _openDetail(context, item, token, baseUrl),
                    icon: const Icon(Icons.edit_note),
                    label: const Text('Expertise'),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Future<void> _openDetail(
  BuildContext context,
  Map<String, dynamic> item,
  String token,
  String baseUrl,
) async {
  await Navigator.of(context).push(
    MaterialPageRoute(
      builder: (_) => ExaminationDetailScreen(
        token: token,
        baseUrl: baseUrl,
        id: (item['id'] as num).toInt(),
      ),
    ),
  );
}
