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 _patientDetailProvider =
    FutureProvider.family<Map<String, dynamic>?, String>((ref, id) async {
      final api = ref.read(apiClientProvider);
      final res = await api.get('/api/doctor/patients/$id');
      return res.data['data'] as Map<String, dynamic>?;
    });

class DoctorPatientDetailPage extends ConsumerWidget {
  final String id;
  const DoctorPatientDetailPage({super.key, required this.id});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final detail = ref.watch(_patientDetailProvider(id));
    return Scaffold(
      backgroundColor: AppColors.background,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        surfaceTintColor: Colors.transparent,
        title: const Text(
          '患者详情',
          style: TextStyle(color: AppColors.textPrimary),
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: AppColors.textPrimary),
          onPressed: () => popRoute(ref),
        ),
      ),
      body: detail.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (_, _) => const Center(child: Text('加载失败')),
        data: (data) => data == null
            ? const Center(child: Text('患者不存在'))
            : _buildBody(data),
      ),
    );
  }

  Widget _buildBody(Map<String, dynamic> data) {
    final profile = data['profile'] as Map<String, dynamic>? ?? {};
    final archive = data['archive'] as Map<String, dynamic>?;
    final latest = data['latestRecords'] as List? ?? [];
    final meds = data['medications'] as List? ?? [];
    final reports = data['reports'] as List? ?? [];
    final followUps = data['followUps'] as List? ?? [];

    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        // 基本信息卡片
        Container(
          padding: const EdgeInsets.all(16),
          decoration: _detailCardDecoration(),
          child: Row(
            children: [
              CircleAvatar(
                radius: 28,
                backgroundColor: AppColors.avatarBg,
                child: Text(
                  (profile['name'] ?? '患')[0],
                  style: const TextStyle(
                    fontSize: 22,
                    color: AppColors.primary,
                  ),
                ),
              ),
              const SizedBox(width: 14),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      profile['name'] ?? '未设置',
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                    Text(
                      profile['phone'] ?? '',
                      style: const TextStyle(
                        fontSize: 13,
                        color: AppColors.textHint,
                      ),
                    ),
                    if (profile['gender'] != null)
                      Text(
                        '${profile['gender']} · ${profile['birthDate'] ?? ''}',
                        style: const TextStyle(
                          fontSize: 12,
                          color: AppColors.textHint,
                        ),
                      ),
                  ],
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 12),

        // 健康档案
        if (archive != null) ...[
          Container(
            padding: const EdgeInsets.all(16),
            decoration: _detailCardDecoration(),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '健康档案',
                  style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
                ),
                const SizedBox(height: 8),
                if (archive['diagnosis'] != null)
                  _row('诊断', archive['diagnosis']),
                if (archive['surgeries'] is List &&
                    (archive['surgeries'] as List).isNotEmpty)
                  _row(
                    '手术史',
                    (archive['surgeries'] as List).map((item) {
                      final surgery = item as Map;
                      final date = surgery['date']?.toString() ?? '';
                      return '${surgery['type'] ?? ''}${date.isEmpty ? '' : ' $date'}';
                    }).join('；'),
                  )
                else if (archive['surgeryType'] != null)
                  _row(
                    '手术史',
                    '${archive['surgeryType']} ${archive['surgeryDate'] ?? ''}',
                  ),
                if (archive['allergies'] != null &&
                    (archive['allergies'] as List).isNotEmpty)
                  _row('过敏史', (archive['allergies'] as List).join('、')),
                if (archive['chronicDiseases'] != null &&
                    (archive['chronicDiseases'] as List).isNotEmpty)
                  _row('慢病', (archive['chronicDiseases'] as List).join('、')),
                if (archive['familyHistory'] != null)
                  _row('家族史', archive['familyHistory']),
              ],
            ),
          ),
          const SizedBox(height: 12),
        ],

        // 最新健康指标
        if (latest.isNotEmpty) ...[
          Container(
            padding: const EdgeInsets.all(16),
            decoration: _detailCardDecoration(),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '健康指标',
                  style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
                ),
                const SizedBox(height: 8),
                ...latest.map((r) {
                  final type = r['metricType']?.toString() ?? '';
                  String val = '';
                  if (type == 'BloodPressure') {
                    val =
                        '${r['systolic'] ?? '--'}/${r['diastolic'] ?? '--'} mmHg';
                  } else {
                    val = '${r['value'] ?? '--'} ${r['unit'] ?? ''}';
                  }
                  return Padding(
                    padding: const EdgeInsets.only(bottom: 4),
                    child: Row(
                      children: [
                        Text(
                          _metricLabel(type),
                          style: const TextStyle(
                            fontSize: 14,
                            color: AppColors.textHint,
                          ),
                        ),
                        const Spacer(),
                        Text(
                          val,
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                            color: r['isAbnormal'] == true
                                ? AppColors.error
                                : AppColors.textPrimary,
                          ),
                        ),
                      ],
                    ),
                  );
                }),
              ],
            ),
          ),
          const SizedBox(height: 12),
        ],

        // 用药列表
        if (meds.isNotEmpty)
          Container(
            padding: const EdgeInsets.all(16),
            decoration: _detailCardDecoration(),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '当前用药',
                  style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
                ),
                const SizedBox(height: 8),
                ...meds.map(
                  (m) => Padding(
                    padding: const EdgeInsets.only(bottom: 4),
                    child: Text(
                      '${m['name']} ${m['dosage'] ?? ''} ${_freqLabel(m['frequency'] ?? '')}',
                      style: const TextStyle(fontSize: 14),
                    ),
                  ),
                ),
              ],
            ),
          ),

        const SizedBox(height: 24),

        // 报告和随访入口
        Row(
          children: [
            Expanded(
              child: _LinkCard(
                '报告 (${reports.length})',
                Icons.description_outlined,
                () {},
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _LinkCard(
                '随访 (${followUps.length})',
                Icons.event_note_outlined,
                () {},
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _row(String label, String? value) => Padding(
    padding: const EdgeInsets.only(bottom: 4),
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          width: 56,
          child: Text(
            label,
            style: const TextStyle(fontSize: 13, color: AppColors.textHint),
          ),
        ),
        Expanded(
          child: Text(value ?? '', style: const TextStyle(fontSize: 14)),
        ),
      ],
    ),
  );

  BoxDecoration _detailCardDecoration() => BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.circular(14),
    border: Border.all(color: AppColors.border),
    boxShadow: AppColors.cardShadowLight,
  );

  String _metricLabel(String t) => switch (t) {
    'BloodPressure' => '血压',
    'HeartRate' => '心率',
    'Glucose' => '血糖',
    'SpO2' => '血氧',
    'Weight' => '体重',
    _ => t,
  };
  String _freqLabel(String f) => switch (f) {
    'Daily' => '每日',
    'Weekly' => '每周',
    'Monthly' => '每月',
    'AsNeeded' => '按需',
    _ => f,
  };
}

class _LinkCard extends StatelessWidget {
  final String label;
  final IconData icon;
  final VoidCallback onTap;
  const _LinkCard(this.label, this.icon, this.onTap);
  @override
  Widget build(BuildContext context) => GestureDetector(
    onTap: onTap,
    child: Container(
      padding: const EdgeInsets.symmetric(vertical: 14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
        border: Border.all(color: AppColors.border),
        boxShadow: AppColors.cardShadowLight,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(icon, size: 18, color: AppColors.primary),
          const SizedBox(width: 6),
          Text(
            label,
            style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
          ),
        ],
      ),
    ),
  );
}
