import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/app_colors.dart';
import '../../core/navigation_provider.dart';
import '../../providers/auth_provider.dart';

final _consListProvider = FutureProvider<List<Map<String, dynamic>>>((
  ref,
) async {
  final api = ref.read(apiClientProvider);
  final res = await api.get('/api/doctor/consultations');
  return (res.data['data'] as List?)?.cast<Map<String, dynamic>>() ?? [];
});

class DoctorConsultationsPage extends ConsumerWidget {
  const DoctorConsultationsPage({super.key});
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final list = ref.watch(_consListProvider);
    return list.when(
      loading: () => const Center(child: CircularProgressIndicator()),
      error: (_, _) => const Center(child: Text('加载失败')),
      data: (items) => items.isEmpty
          ? const Center(
              child: Text('暂无问诊', style: TextStyle(color: AppColors.textHint)),
            )
          : ListView.builder(
              padding: const EdgeInsets.all(16),
              itemCount: items.length,
              itemBuilder: (_, i) {
                final c = items[i];
                final status = c['status'] ?? '';
                final msg = c['lastMessage'] as Map<String, dynamic>?;
                return Container(
                  margin: const EdgeInsets.only(bottom: 8),
                  padding: const EdgeInsets.all(14),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(14),
                    border: Border.all(color: AppColors.border),
                    boxShadow: AppColors.cardShadowLight,
                  ),
                  child: ListTile(
                    contentPadding: EdgeInsets.zero,
                    leading: CircleAvatar(
                      radius: 22,
                      backgroundColor: AppColors.avatarBg,
                      child: Text(
                        (c['patientName'] ?? '?')[0],
                        style: const TextStyle(color: AppColors.primary),
                      ),
                    ),
                    title: Text(
                      c['patientName'] ?? c['patientPhone'] ?? '',
                      style: const TextStyle(fontWeight: FontWeight.w600),
                    ),
                    subtitle: Text(
                      msg?['content'] ?? '暂无消息',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    trailing: _StatusBadge(status),
                    onTap: () => pushRoute(
                      ref,
                      'doctorChat',
                      params: {'id': c['id']?.toString() ?? ''},
                    ),
                  ),
                );
              },
            ),
    );
  }
}

class _StatusBadge extends StatelessWidget {
  final String status;
  const _StatusBadge(this.status);
  @override
  Widget build(BuildContext context) {
    final (label, color) = switch (status) {
      'AiTalking' => ('AI中', AppColors.primary),
      'WaitingDoctor' => ('等待医生', const Color(0xFFF59E0B)),
      'DoctorReplied' => ('已回复', const Color(0xFF10B981)),
      'Closed' => ('已关闭', const Color(0xFF9CA3AF)),
      _ => (status, const Color(0xFF9CA3AF)),
    };
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Text(
        label,
        style: TextStyle(
          fontSize: 12,
          color: color,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }
}
