import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/app_colors.dart';
import '../../providers/auth_provider.dart';
import '../doctor/doctor_home_page.dart' show doctorPageProvider;

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

class DoctorDashboardPage extends ConsumerWidget {
  const DoctorDashboardPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final dash = ref.watch(_dashboardProvider);
    final hasProfile = dash is AsyncData && dash.value != null;

    return RefreshIndicator(
      onRefresh: () => ref.refresh(_dashboardProvider.future),
      child: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          if (!hasProfile)
            Container(
              padding: const EdgeInsets.all(14),
              margin: const EdgeInsets.only(bottom: 16),
              decoration: BoxDecoration(
                color: AppColors.infoLight,
                borderRadius: BorderRadius.circular(14),
                border: Border.all(color: AppColors.border),
                boxShadow: AppColors.cardShadowLight,
              ),
              child: Row(
                children: [
                  const Icon(
                    Icons.info_outline,
                    color: AppColors.primary,
                    size: 20,
                  ),
                  const SizedBox(width: 10),
                  const Expanded(
                    child: Text(
                      '请完善个人信息',
                      style: TextStyle(color: AppColors.primary, fontSize: 14),
                    ),
                  ),
                  GestureDetector(
                    onTap: () => {},
                    child: const Text(
                      '去完善',
                      style: TextStyle(
                        color: AppColors.primary,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ],
              ),
            ),

          dash.when(
            loading: () => const Center(child: CircularProgressIndicator()),
            error: (_, _) => const Center(child: Text('加载失败')),
            data: (data) => _buildContent(context, ref, data),
          ),
        ],
      ),
    );
  }

  Widget _buildContent(
    BuildContext context,
    WidgetRef ref,
    Map<String, dynamic>? data,
  ) {
    final stats = data?['stats'] as Map<String, dynamic>? ?? {};

    return Column(
      children: [
        // 统计卡片
        Row(
          children: [
            Expanded(
              child: _StatCard(
                '患者总数',
                '${stats['totalPatients'] ?? 0}',
                Icons.people,
                const Color(0xFF3B82F6),
                () {
                  ref.read(doctorPageProvider.notifier).set('patients');
                },
              ),
            ),
            const SizedBox(width: 10),
            Expanded(
              child: _StatCard(
                '进行中问诊',
                '${stats['activeConsultations'] ?? 0}',
                Icons.chat,
                const Color(0xFF10B981),
                () {
                  ref.read(doctorPageProvider.notifier).set('consultations');
                },
              ),
            ),
          ],
        ),
        const SizedBox(height: 10),
        Row(
          children: [
            Expanded(
              child: _StatCard(
                '待审核报告',
                '${stats['pendingReports'] ?? 0}',
                Icons.description,
                const Color(0xFFF59E0B),
                () {
                  ref.read(doctorPageProvider.notifier).set('reports');
                },
              ),
            ),
            const SizedBox(width: 10),
            Expanded(
              child: _StatCard(
                '今日随访',
                '${stats['todayFollowUps'] ?? 0}',
                Icons.event_note,
                const Color(0xFFEF4444),
                () {
                  ref.read(doctorPageProvider.notifier).set('followups');
                },
              ),
            ),
          ],
        ),
        const SizedBox(height: 20),

        // 待办：未回复问诊
        _TodoSection(
          title: '待回复问诊',
          icon: Icons.chat_outlined,
          color: const Color(0xFF10B981),
          items:
              (data?['pendingConsultations'] as List?)
                  ?.cast<Map<String, dynamic>>() ??
              [],
          itemLabel: (m) => m['patientName'] ?? '',
          itemSubtitle: (m) => '待回复',
          onTap: (m) {
            ref.read(doctorPageProvider.notifier).set('consultations');
          },
        ),

        // 待办：待审核报告
        _TodoSection(
          title: '待审核报告',
          icon: Icons.description_outlined,
          color: const Color(0xFFF59E0B),
          items:
              (data?['pendingReports'] as List?)
                  ?.cast<Map<String, dynamic>>() ??
              [],
          itemLabel: (m) => '${m['patientName'] ?? ''}',
          itemSubtitle: (m) => '${m['category'] ?? ''}',
          onTap: (m) {
            ref.read(doctorPageProvider.notifier).set('reports');
          },
        ),

        // 今日随访
        _TodoSection(
          title: '今日随访',
          icon: Icons.event_note_outlined,
          color: const Color(0xFFEF4444),
          items:
              (data?['todayFollowUps'] as List?)
                  ?.cast<Map<String, dynamic>>() ??
              [],
          itemLabel: (m) => '${m['title'] ?? ''}',
          itemSubtitle: (m) => '${m['patientName'] ?? ''}',
          onTap: (m) {
            ref.read(doctorPageProvider.notifier).set('followups');
          },
        ),
      ],
    );
  }
}

class _StatCard extends StatelessWidget {
  final String label;
  final String value;
  final IconData icon;
  final Color color;
  final VoidCallback onTap;

  const _StatCard(this.label, this.value, this.icon, this.color, this.onTap);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: AppColors.border),
          boxShadow: AppColors.cardShadowLight,
        ),
        child: Row(
          children: [
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: color.withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Icon(icon, color: color, size: 20),
            ),
            const SizedBox(width: 12),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  value,
                  style: const TextStyle(
                    fontSize: 22,
                    fontWeight: FontWeight.w700,
                    color: AppColors.textPrimary,
                  ),
                ),
                Text(
                  label,
                  style: const TextStyle(
                    fontSize: 12,
                    color: AppColors.textHint,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

class _TodoSection extends StatelessWidget {
  final String title;
  final IconData icon;
  final Color color;
  final List<Map<String, dynamic>> items;
  final String Function(Map<String, dynamic>) itemLabel;
  final String Function(Map<String, dynamic>) itemSubtitle;
  final void Function(Map<String, dynamic>) onTap;

  const _TodoSection({
    required this.title,
    required this.icon,
    required this.color,
    required this.items,
    required this.itemLabel,
    required this.itemSubtitle,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    if (items.isEmpty) return const SizedBox.shrink();
    return Padding(
      padding: const EdgeInsets.only(bottom: 16),
      child: Container(
        padding: const EdgeInsets.all(14),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: AppColors.border),
          boxShadow: AppColors.cardShadowLight,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(icon, size: 18, color: color),
                const SizedBox(width: 6),
                Text(
                  title,
                  style: const TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w600,
                    color: AppColors.textPrimary,
                  ),
                ),
                const Spacer(),
                Text(
                  '${items.length}项',
                  style: const TextStyle(
                    fontSize: 12,
                    color: AppColors.textHint,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            ...items
                .take(5)
                .map(
                  (m) => GestureDetector(
                    onTap: () => onTap(m),
                    child: Container(
                      padding: const EdgeInsets.symmetric(vertical: 8),
                      decoration: const BoxDecoration(
                        border: Border(
                          top: BorderSide(color: AppColors.divider),
                        ),
                      ),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text(
                              itemLabel(m),
                              style: const TextStyle(
                                fontSize: 14,
                                color: AppColors.textPrimary,
                              ),
                            ),
                          ),
                          Text(
                            itemSubtitle(m),
                            style: const TextStyle(
                              fontSize: 12,
                              color: AppColors.textHint,
                            ),
                          ),
                          const SizedBox(width: 4),
                          const Icon(
                            Icons.chevron_right,
                            size: 16,
                            color: AppColors.textHint,
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
          ],
        ),
      ),
    );
  }
}
