import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../core/navigation_provider.dart';
import '../providers/auth_provider.dart';
import '../providers/data_providers.dart';
import '../providers/chat_provider.dart';
import 'service_package_card.dart';

/// 侧滑抽屉——彩色分区卡片式设计
class HealthDrawer extends ConsumerWidget {
  const HealthDrawer({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final auth = ref.watch(authProvider);
    final user = auth.user;
    final latestHealth = ref.watch(latestHealthProvider);
    final conversations = ref.watch(conversationListProvider);

    return Drawer(
      width: MediaQuery.of(context).size.width * 0.82,
      backgroundColor: const Color(0xFFFAFBFE),
      child: SafeArea(
        child: ListView(
          padding: const EdgeInsets.fromLTRB(16, 8, 16, 20),
          children: [
            // ════════════ 用户区 ════════════
            _SectionCard(
              color: const Color(0xFF635BFF),
              gradientColors: [const Color(0xFF7C74FF), const Color(0xFF5248E8)],
              child: GestureDetector(
                onTap: () => pushRoute(ref, 'profile'),
                child: Padding(
                  padding: const EdgeInsets.all(18),
                  child: Row(children: [
                    Container(
                      width: 52, height: 52,
                      decoration: BoxDecoration(
                        gradient: LinearGradient(colors: [Colors.white.withAlpha(40), Colors.white.withAlpha(15)]),
                        shape: BoxShape.circle,
                        border: Border.all(color: Colors.white30, width: 1.5),
                      ),
                      child: user?.avatarUrl != null
                          ? ClipOval(child: Image.network(user!.avatarUrl!, fit: BoxFit.cover, errorBuilder: (_, e, s) => _defaultAvatar()))
                          : _defaultAvatar(),
                    ),
                    const SizedBox(width: 14),
                    Expanded(child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(user?.name ?? '未设置昵称', style: const TextStyle(fontSize: 17, fontWeight: FontWeight.w700, color: Colors.white)),
                        const SizedBox(height: 2),
                        Text(user?.phone ?? '未登录', style: TextStyle(fontSize: 12, color: Colors.white70)),
                      ],
                    )),
                    Icon(Icons.chevron_right, size: 18, color: Colors.white54),
                  ]),
                ),
              ),
            ),

            const SizedBox(height: 10),

            // ════════════ 健康概览区 ════════════
            _SectionCard(
              color: Colors.white,
              gradientColors: null,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.fromLTRB(16, 14, 16, 6),
                    child: Row(children: [
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                        decoration: BoxDecoration(
                          color: const Color(0xFF6C5CE7).withAlpha(15),
                          borderRadius: BorderRadius.circular(6),
                        ),
                        child: const Row(mainAxisSize: MainAxisSize.min, children: [
                          Icon(Icons.monitor_heart_rounded, size: 13, color: Color(0xFF6C5CE7)),
                          SizedBox(width: 4),
                          Text('健康概览', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xFF6C5CE7))),
                        ]),
                      ),
                      const Spacer(),
                      GestureDetector(
                        onTap: () => pushRoute(ref, 'trend'),
                        child: const Padding(padding: EdgeInsets.all(4), child: Text('详情', style: TextStyle(fontSize: 11, color: Color(0xFF888888)))),
                      ),
                    ]),
                  ),
                  latestHealth.when(
                    data: (data) => Padding(
                      padding: const EdgeInsets.fromLTRB(12, 4, 12, 14),
                      child: Row(children: [
                        _MiniMetric(icon: Icons.favorite_rounded, label: '血压', value: _bpText(data['BloodPressure']), onTap: () => pushRoute(ref, 'trend', params: {'type': 'blood_pressure'})),
                        _MiniMetric(icon: Icons.monitor_heart_outlined, label: '心率', value: _metricVal(data['HeartRate']), onTap: () => pushRoute(ref, 'trend', params: {'type': 'heart_rate'})),
                        _MiniMetric(icon: Icons.bloodtype_outlined, label: '血糖', value: _metricVal(data['Glucose']), onTap: () => pushRoute(ref, 'trend', params: {'type': 'glucose'})),
                        _MiniMetric(icon: Icons.air_outlined, label: '血氧', value: _metricVal(data['SpO2']), onTap: () => pushRoute(ref, 'trend', params: {'type': 'spo2'})),
                        _MiniMetric(icon: Icons.monitor_weight_outlined, label: '体重', value: _metricVal(data['Weight']), onTap: () => pushRoute(ref, 'trend', params: {'type': 'weight'})),
                      ]),
                    ),
                    loading: () => const Padding(padding: EdgeInsets.symmetric(vertical: 20), child: Center(child: SizedBox(width: 22, height: 22, child: CircularProgressIndicator(strokeWidth: 2, color: Color(0xFF6C5CE7))))),
                    error: (_, __) => Padding(
                      padding: const EdgeInsets.fromLTRB(12, 4, 12, 14),
                      child: Row(children: [
                        _MiniMetric(icon: Icons.favorite_rounded, label: '血压', value: '--'),
                        _MiniMetric(icon: Icons.monitor_heart_outlined, label: '心率', value: '--'),
                        _MiniMetric(icon: Icons.bloodtype_outlined, label: '血糖', value: '--'),
                        _MiniMetric(icon: Icons.air_outlined, label: '血氧', value: '--'),
                        _MiniMetric(icon: Icons.monitor_weight_outlined, label: '体重', value: '--'),
                      ]),
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 10),

            // ════════════ 功能区（横向均布）════════════
            _SectionCard(
              color: Colors.white,
              gradientColors: null,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.fromLTRB(16, 14, 16, 6),
                    child: Row(children: [
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                        decoration: BoxDecoration(
                          color: const Color(0xFFF0A060).withAlpha(15),
                          borderRadius: BorderRadius.circular(6),
                        ),
                        child: const Row(mainAxisSize: MainAxisSize.min, children: [
                          Icon(Icons.apps_rounded, size: 13, color: Color(0xFFF0A060)),
                          SizedBox(width: 4),
                          Text('功能', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xFFF0A060))),
                        ]),
                      ),
                    ]),
                  ),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(12, 4, 12, 14),
                    child: Row(children: [
                      _FeatureChip(icon: Icons.description_outlined, label: '报告管理', onTap: () => pushRoute(ref, 'reports')),
                      _FeatureChip(icon: Icons.calendar_today_outlined, label: '健康日历', onTap: () => pushRoute(ref, 'calendar')),
                      _FeatureChip(icon: Icons.restaurant_outlined, label: '饮食记录', onTap: () => pushRoute(ref, 'dietRecords')),
                      _FeatureChip(icon: Icons.event_note_outlined, label: '复查随访', onTap: () => pushRoute(ref, 'followups')),
                    ]),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 10),

            // ════════════ 产品服务包 ════════════
            const ServicePackageCard(compact: true),

            const SizedBox(height: 10),

            // ════════════ 历史对话区 ════════════
            _SectionCard(
              color: Colors.white,
              gradientColors: null,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.fromLTRB(16, 14, 16, 4),
                    child: Row(children: [
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                        decoration: BoxDecoration(
                          color: const Color(0xFF4D96FF).withAlpha(15),
                          borderRadius: BorderRadius.circular(6),
                        ),
                        child: const Row(mainAxisSize: MainAxisSize.min, children: [
                          Icon(Icons.history_rounded, size: 13, color: Color(0xFF4D96FF)),
                          SizedBox(width: 4),
                          Text('历史对话', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xFF4D96FF))),
                        ]),
                      ),
                      const Spacer(),
                      GestureDetector(
                        onTap: () async {
                          final api = ref.read(apiClientProvider);
                          for (final c in conversations.value ?? []) {
                            try { await api.delete('/api/ai/conversations/${c.id}'); } catch (_) {}
                          }
                          ref.invalidate(conversationListProvider);
                        },
                        child: const Padding(padding: EdgeInsets.all(4), child: Text('清理', style: TextStyle(fontSize: 11, color: Color(0xFFAAAAAA)))),
                      ),
                    ]),
                  ),
                  _buildConversationList(context, ref, conversations),
                ],
              ),
            ),

            const SizedBox(height: 10),

            // ════════════ 设置区 ════════════
            _SectionCard(
              color: const Color(0xFFF5F5F7),
              gradientColors: null,
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  onTap: () => pushRoute(ref, 'settings'),
                  borderRadius: BorderRadius.circular(16),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 14),
                    child: Row(children: [
                      Container(
                        width: 34, height: 34,
                        decoration: BoxDecoration(
                          color: const Color(0xFFEEEEEE),
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: const Icon(Icons.settings_outlined, size: 18, color: Color(0xFF666666)),
                      ),
                      const SizedBox(width: 12),
                      const Expanded(child: Text('设置', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500, color: Color(0xFF333333)))),
                      const Icon(Icons.chevron_right, size: 16, color: Color(0xFFCCCCCC)),
                    ]),
                  ),
                ),
              ),
            ),

            const SizedBox(height: 6),
          ],
        ),
      ),
    );
  }

  static Widget _defaultAvatar() => const Icon(Icons.person, size: 26, color: Colors.white70);

  String _bpText(dynamic bp) {
    if (bp == null) return '--';
    if (bp is Map) return '${bp['systolic'] ?? '--'}/${bp['diastolic'] ?? '--'}';
    return '--';
  }

  String _metricVal(dynamic metric) {
    if (metric == null) return '--';
    if (metric is Map) { final v = metric['value']; return v?.toString() ?? '--'; }
    return metric.toString();
  }

  Widget _buildConversationList(BuildContext context, WidgetRef ref, AsyncValue<List<ConversationItem>> conversations) {
    return conversations.when(
      data: (items) {
        if (items.isEmpty) {
          return const Padding(
            padding: EdgeInsets.symmetric(vertical: 16),
            child: Center(
              child: Text('暂无历史对话', style: TextStyle(color: Color(0xFFBBBBBB), fontSize: 13)),
            ),
          );
        }
        return Padding(
          padding: const EdgeInsets.fromLTRB(8, 6, 8, 14),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: items.map((item) => _ConversationItem(
              item: item,
              onTap: () {
                ref.read(chatProvider.notifier).loadConversation(item.id);
                Navigator.of(context).pop();
              },
              onDelete: () async {
                try {
                  await ref.read(apiClientProvider).delete('/api/ai/conversations/${item.id}');
                  ref.invalidate(conversationListProvider);
                } catch (_) {}
              },
            )).toList(),
          ),
        );
      },
      loading: () => const Padding(
        padding: EdgeInsets.symmetric(vertical: 16),
        child: Center(
          child: SizedBox(
            width: 20,
            height: 20,
            child: CircularProgressIndicator(strokeWidth: 2, color: Color(0xFF4D96FF)),
          ),
        ),
      ),
      error: (Object err, StackTrace st) => const Padding(
        padding: EdgeInsets.symmetric(vertical: 16),
        child: Center(
          child: Text('加载失败', style: TextStyle(color: Color(0xFFBBBBBB), fontSize: 13)),
        ),
      ),
    );
  }
}

// ═══════════════════════════════════════════════════════════════
// 分区卡片容器 —— 带圆角、阴影和微动效
// ═══════════════════════════════════════════════════════════════

class _SectionCard extends StatelessWidget {
  final Widget child;
  final Color color;
  final List<Color>? gradientColors;

  const _SectionCard({required this.child, required this.color, this.gradientColors});

  @override
  Widget build(BuildContext context) {
    return TweenAnimationBuilder<double>(
      tween: Tween(begin: 0.0, end: 1.0),
      duration: const Duration(milliseconds: 500),
      curve: Curves.easeOutCubic,
      builder: (context, value, child) => Transform.translate(
        offset: Offset(0, 8 * (1 - value)),
        child: Opacity(opacity: value, child: child),
      ),
      child: Container(
        decoration: BoxDecoration(
          color: gradientColors == null ? color : null,
          gradient: gradientColors != null ? LinearGradient(
            colors: gradientColors!,
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ) : null,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
              color: (gradientColors?.first ?? color).withAlpha(25),
              blurRadius: 12,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        clipBehavior: Clip.antiAlias,
        child: child,
      ),
    );
  }
}

// ═══════════════════════════════════════════════════════════════
// 健康指标小方块
// ═══════════════════════════════════════════════════════════════

class _MiniMetric extends StatelessWidget {
  final IconData icon;
  final String label;
  final String value;
  final VoidCallback? onTap;
  const _MiniMetric({required this.icon, required this.label, required this.value, this.onTap});

  static const _c = Color(0xFF6C5CE7);

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: GestureDetector(
        onTap: onTap,
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 3),
          padding: const EdgeInsets.symmetric(vertical: 10),
          decoration: BoxDecoration(
            color: _c.withAlpha(10),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(mainAxisSize: MainAxisSize.min, children: [
            Icon(icon, size: 18, color: _c),
            const SizedBox(height: 6),
            Text(value, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w700, color: Color(0xFF1A1A1A)), maxLines: 1, overflow: TextOverflow.ellipsis),
            const SizedBox(height: 2),
            Text(label, style: TextStyle(fontSize: 10, color: Colors.grey[500])),
          ]),
        ),
      ),
    );
  }
}

// ═══════════════════════════════════════════════════════════════
// 功能按钮（横向）
// ═══════════════════════════════════════════════════════════════

class _FeatureChip extends StatelessWidget {
  final IconData icon;
  final String label;
  final VoidCallback onTap;

  const _FeatureChip({
    required this.icon,
    required this.label,
    required this.onTap,
  });

  static const _c = Color(0xFF6C5CE7);

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: GestureDetector(
        onTap: onTap,
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 3),
          padding: const EdgeInsets.symmetric(vertical: 10),
          decoration: BoxDecoration(
            color: _c.withAlpha(10),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Column(mainAxisSize: MainAxisSize.min, children: [
            Icon(icon, size: 18, color: _c),
            const SizedBox(height: 6),
            Text(label, style: const TextStyle(fontSize: 10, fontWeight: FontWeight.w500, color: Color(0xFF666666))),
          ]),
        ),
      ),
    );
  }
}

// ═══════════════════════════════════════════════════════════════
// 历史对话项
// ═══════════════════════════════════════════════════════════════

class _ConversationItem extends StatelessWidget {
  final ConversationItem item;
  final VoidCallback? onTap;
  final VoidCallback? onDelete;

  const _ConversationItem({required this.item, this.onTap, this.onDelete});

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 2),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
        border: Border.all(color: const Color(0xFFEEEEEE)),
      ),
      child: ListTile(
        onTap: onTap,
        contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
        leading: Container(
          width: 32, height: 32,
          decoration: BoxDecoration(
            color: const Color(0xFFEDEAFF),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Icon(_getAgentIcon(item.agent), size: 15, color: const Color(0xFF6C5CE7)),
        ),
        title: Text(item.title, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: Color(0xFF333333))),
        subtitle: Text(item.lastMessage, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 11, color: Colors.grey[500])),
        trailing: GestureDetector(
          onTap: onDelete,
          child: const Padding(
            padding: EdgeInsets.all(8),
            child: Icon(Icons.close, size: 16, color: Color(0xFFBBBBBB)),
          ),
        ),
        dense: true,
        visualDensity: VisualDensity.compact,
      ),
    );
  }

  IconData _getAgentIcon(ActiveAgent agent) {
    return switch (agent) {
      ActiveAgent.health => Icons.health_and_safety_outlined,
      ActiveAgent.diet => Icons.restaurant_outlined,
      ActiveAgent.medication => Icons.medication_outlined,
      ActiveAgent.report => Icons.description_outlined,
      ActiveAgent.exercise => Icons.directions_run_outlined,
      ActiveAgent.consultation => Icons.chat_bubble_outline,
      _ => Icons.chat_bubble_outline,
    };
  }

  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final diff = now.difference(time);
    if (diff.inMinutes < 60) return '${diff.inMinutes}分钟前';
    if (diff.inHours < 24) return '${diff.inHours}小时前';
    if (diff.inDays < 7) return '${diff.inDays}天前';
    return '${time.month}/${time.day}';
  }
}

