import 'dart:convert';
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';
import '../../utils/backoffice_formatters.dart';
import '../../widgets/app_toast.dart';
import '../../widgets/backoffice_ui.dart';

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

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

  @override
  ConsumerState<DoctorReportDetailPage> createState() =>
      _DoctorReportDetailPageState();
}

class _DoctorReportDetailPageState
    extends ConsumerState<DoctorReportDetailPage> {
  String _severity = '';
  String _comment = '';
  String _recommendation = '';
  bool _submitting = false;
  bool _submitted = false;

  static const _severityOptions = ['Normal', 'Abnormal', 'Severe', 'Critical'];
  static const _severityLabels = {
    'Normal': '正常',
    'Abnormal': '异常',
    'Severe': '严重',
    'Critical': '危急',
  };
  static const _severityColors = {
    'Normal': 0xFF10B981,
    'Abnormal': 0xFFF59E0B,
    'Severe': 0xFFEF4444,
    'Critical': 0xFF991B1B,
  };

  static const _templates = [
    '药物剂量调整',
    '复查建议',
    '生活方式干预',
    '进一步检查',
    '专科转诊',
    '无需特殊处理',
  ];

  Future<void> _submitReview() async {
    if (_severity.isEmpty) {
      AppToast.show(context, '请选择严重程度', type: AppToastType.warning);
      return;
    }
    setState(() => _submitting = true);
    try {
      final api = ref.read(apiClientProvider);
      await api.post(
        '/api/doctor/reports/${widget.id}/review',
        data: {
          'severity': _severity,
          'comment': _comment,
          'recommendation': _recommendation,
        },
      );
      if (!mounted) return;
      setState(() => _submitted = true);
      ref.invalidate(_reportDetailProvider(widget.id));
      if (mounted) {
        AppToast.show(context, '审核提交成功', type: AppToastType.success);
      }
    } catch (e) {
      if (mounted) {
        AppToast.show(context, '提交失败: $e', type: AppToastType.error);
      }
    } finally {
      if (mounted) setState(() => _submitting = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final detail = ref.watch(_reportDetailProvider(widget.id));

    return Scaffold(
      backgroundColor: AppColors.background,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        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: BackofficeSurface(
        child: detail.when(
          loading: () => const BackofficeLoadingState(message: '正在加载报告详情'),
          error: (_, _) => BackofficeErrorState(
            onRetry: () => ref.invalidate(_reportDetailProvider(widget.id)),
          ),
          data: (data) => data == null
              ? const BackofficeEmptyState(
                  icon: Icons.description_outlined,
                  title: '报告不存在',
                )
              : _buildBody(data),
        ),
      ),
    );
  }

  Widget _buildBody(Map<String, dynamic> data) {
    final aiSummary = data['aiSummary'] as String?;
    final aiIndicators = _parseIndicators(data['aiIndicators']?.toString());
    final reviewed = data['status'] == 'DoctorReviewed';
    final doctorComment = data['doctorComment'] as String?;
    final doctorRec = data['doctorRecommendation'] as String?;
    final severity = data['severity'] as String?;
    final fileUrl = data['fileUrl'] as String?;

    return ListView(
      keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
      padding: const EdgeInsets.all(16),
      children: [
        // 患者+分类信息
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(14),
            border: Border.all(color: AppColors.border),
            boxShadow: AppColors.cardShadowLight,
          ),
          child: Row(
            children: [
              CircleAvatar(
                radius: 24,
                backgroundColor: AppColors.avatarBg,
                child: Text(
                  backofficeInitial(data['patientName']),
                  style: const TextStyle(color: AppColors.primary),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      data['patientName'] ?? '',
                      style: const TextStyle(
                        fontWeight: FontWeight.w600,
                        fontSize: 16,
                      ),
                    ),
                    Text(
                      '${data['category'] ?? ''} · ${data['fileType'] ?? ''}',
                      style: const TextStyle(
                        fontSize: 13,
                        color: AppColors.textHint,
                      ),
                    ),
                  ],
                ),
              ),
              _StatusTag(data['status']?.toString() ?? ''),
            ],
          ),
        ),

        // AI预分析摘要
        if (aiSummary != null && aiSummary.isNotEmpty) ...[
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(14),
              border: Border.all(color: AppColors.border),
              boxShadow: AppColors.cardShadowLight,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Container(
                      width: 4,
                      height: 16,
                      decoration: BoxDecoration(
                        color: AppColors.primary,
                        borderRadius: BorderRadius.circular(2),
                      ),
                    ),
                    const SizedBox(width: 8),
                    const Text(
                      'AI 预分析',
                      style: TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 8),
                Text(
                  aiSummary,
                  style: const TextStyle(
                    fontSize: 14,
                    color: AppColors.textSecondary,
                    height: 1.5,
                  ),
                ),
              ],
            ),
          ),
        ],

        // AI指标表格
        if (aiIndicators.isNotEmpty) ...[
          const SizedBox(height: 12),
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(14),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '指标检测',
                  style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
                ),
                const SizedBox(height: 8),
                ...aiIndicators.map(
                  (ind) => Padding(
                    padding: const EdgeInsets.only(bottom: 6),
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            ind['name'] ?? '',
                            style: const TextStyle(fontSize: 14),
                          ),
                        ),
                        Text(
                          ind['value'] ?? '',
                          style: const TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        if (ind['unit'] != null)
                          Text(
                            ' ${ind['unit']}',
                            style: const TextStyle(
                              fontSize: 12,
                              color: AppColors.textHint,
                            ),
                          ),
                        const SizedBox(width: 8),
                        if (ind['status'] != null)
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 6,
                              vertical: 2,
                            ),
                            decoration: BoxDecoration(
                              color: _indicatorColor(
                                ind['status']!,
                              ).withValues(alpha: 0.1),
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Text(
                              ind['status']!,
                              style: TextStyle(
                                fontSize: 11,
                                color: _indicatorColor(ind['status']!),
                              ),
                            ),
                          ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],

        // 查看原始报告
        if (fileUrl != null && fileUrl.isNotEmpty) ...[
          const SizedBox(height: 12),
          SizedBox(
            width: double.infinity,
            child: OutlinedButton.icon(
              onPressed: () {
                pushRoute(
                  ref,
                  'reportOriginal',
                  params: {'url': fileUrl, 'title': '原始报告'},
                );
              },
              icon: const Icon(Icons.visibility, size: 18),
              label: const Text('查看原始报告'),
              style: OutlinedButton.styleFrom(
                foregroundColor: AppColors.primary,
                side: const BorderSide(color: AppColors.border),
                padding: const EdgeInsets.symmetric(vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(14),
                ),
              ),
            ),
          ),
        ],

        // 医生审核区（未审核时显示）
        if (!reviewed && !_submitted) ...[
          const SizedBox(height: 20),
          Container(
            width: double.infinity,
            height: 1,
            color: AppColors.divider,
          ),
          const SizedBox(height: 16),
          const Text(
            '医生审核',
            style: TextStyle(
              fontSize: 17,
              fontWeight: FontWeight.w700,
              color: AppColors.textPrimary,
            ),
          ),
          const SizedBox(height: 14),

          // 严重程度
          const Text(
            '严重程度',
            style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
          ),
          const SizedBox(height: 8),
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: _severityOptions
                .map(
                  (s) => GestureDetector(
                    onTap: () => setState(() => _severity = s),
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 10,
                      ),
                      decoration: BoxDecoration(
                        color: _severity == s
                            ? Color(_severityColors[s]!)
                            : Colors.white,
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(
                          color: _severity == s
                              ? Color(_severityColors[s]!)
                              : AppColors.border,
                        ),
                      ),
                      child: Text(
                        _severityLabels[s]!,
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                          color: _severity == s
                              ? Colors.white
                              : AppColors.textSecondary,
                        ),
                      ),
                    ),
                  ),
                )
                .toList(),
          ),

          const SizedBox(height: 16),

          // 建议模板
          const Text(
            '建议模板（可多选）',
            style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
          ),
          const SizedBox(height: 8),
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: _templates.map((t) {
              final selected = _recommendation.contains(t);
              return GestureDetector(
                onTap: () {
                  setState(() {
                    if (selected) {
                      _recommendation = _recommendation
                          .replaceAll('$t、', '')
                          .replaceAll('、$t', '')
                          .replaceAll(t, '');
                    } else {
                      _recommendation = _recommendation.isEmpty
                          ? t
                          : '$_recommendation、$t';
                    }
                  });
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 14,
                    vertical: 8,
                  ),
                  decoration: BoxDecoration(
                    color: selected ? AppColors.primarySoft : Colors.white,
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(
                      color: selected ? AppColors.primary : AppColors.border,
                    ),
                  ),
                  child: Text(
                    t,
                    style: TextStyle(
                      fontSize: 13,
                      color: selected
                          ? AppColors.primary
                          : AppColors.textSecondary,
                    ),
                  ),
                ),
              );
            }).toList(),
          ),

          const SizedBox(height: 16),

          // 自定义评语
          const Text(
            '评语',
            style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
          ),
          const SizedBox(height: 8),
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(14),
              border: Border.all(color: AppColors.border),
              boxShadow: AppColors.cardShadowLight,
            ),
            child: TextField(
              maxLines: 5,
              decoration: InputDecoration(
                hintText: '输入审核评语（可选）',
                hintStyle: const TextStyle(
                  fontSize: 14,
                  color: AppColors.textHint,
                ),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(14),
                  borderSide: const BorderSide(color: Colors.transparent),
                ),
                contentPadding: const EdgeInsets.all(16),
              ),
              onChanged: (v) => _comment = v,
            ),
          ),

          const SizedBox(height: 20),
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: _submitting ? null : _submitReview,
              style: ElevatedButton.styleFrom(
                backgroundColor: AppColors.primary,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(vertical: 14),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(14),
                ),
              ),
              child: _submitting
                  ? const CircularProgressIndicator(color: Colors.white)
                  : const Text('提交审核', style: TextStyle(fontSize: 16)),
            ),
          ),
        ],

        // 已审核结果
        if (reviewed || _submitted) ...[
          const SizedBox(height: 20),
          Container(
            width: double.infinity,
            height: 1,
            color: AppColors.divider,
          ),
          const SizedBox(height: 16),
          Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(14),
              border: Border.all(color: const Color(0xFFD1FAE5)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    const Icon(
                      Icons.check_circle,
                      color: Color(0xFF10B981),
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    const Text(
                      '审核已完成',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w700,
                        color: Color(0xFF10B981),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                if (severity != null)
                  _infoRow('严重程度', _severityLabels[severity] ?? severity),
                if (doctorRec != null && doctorRec.isNotEmpty)
                  _infoRow('建议', doctorRec),
                if (doctorComment != null && doctorComment.isNotEmpty)
                  _infoRow('评语', doctorComment),
              ],
            ),
          ),
        ],
        const SizedBox(height: 24),
      ],
    );
  }

  List<Map<String, String>> _parseIndicators(String? raw) {
    if (raw == null || raw.isEmpty) return [];
    try {
      final list = jsonDecode(raw);
      if (list is List) {
        return list.map((e) => Map<String, String>.from(e as Map)).toList();
      }
    } catch (_) {}
    return [];
  }

  Color _indicatorColor(String s) => switch (s) {
    '正常' || 'normal' => const Color(0xFF10B981),
    '偏高' || 'high' => const Color(0xFFEF4444),
    '偏低' || 'low' => const Color(0xFFF59E0B),
    _ => AppColors.textHint,
  };

  Widget _infoRow(String label, String value) => Padding(
    padding: const EdgeInsets.only(bottom: 6),
    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))),
      ],
    ),
  );
}

class _StatusTag extends StatelessWidget {
  final String s;
  const _StatusTag(this.s);
  @override
  Widget build(BuildContext context) {
    final (label, color) = s == 'DoctorReviewed'
        ? ('已审核', const Color(0xFF10B981))
        : s == 'PendingDoctor'
        ? ('待审核', const Color(0xFFF59E0B))
        : (s, AppColors.textHint);
    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)),
    );
  }
}
