import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../../core/app_colors.dart';
import '../../core/app_theme.dart';
import '../../core/navigation_provider.dart';
import '../../providers/chat_provider.dart';
import '../../providers/conversation_history_provider.dart';
import '../../widgets/app_toast.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final async = ref.watch(conversationHistoryProvider);

    return GradientScaffold(
      appBar: AppBar(
        backgroundColor: Colors.white.withValues(alpha: 0.9),
        title: const Text('对话记录'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => popRoute(ref),
        ),
        actions: [
          TextButton(
            onPressed: () => _confirmClearAll(context, ref),
            child: const Text(
              '清空',
              style: TextStyle(
                color: AppColors.error,
                fontWeight: FontWeight.w800,
              ),
            ),
          ),
        ],
      ),
      body: RefreshIndicator(
        onRefresh: () =>
            ref.read(conversationHistoryProvider.notifier).refresh(),
        child: async.when(
          loading: () => const Center(child: CircularProgressIndicator()),
          error: (e, _) => _ErrorBlock(
            message: '历史记录加载失败',
            onRetry: () =>
                ref.read(conversationHistoryProvider.notifier).refresh(),
          ),
          data: (list) => list.isEmpty
              ? const _EmptyHint()
              : ListView.separated(
                  padding: const EdgeInsets.fromLTRB(16, 14, 16, 24),
                  itemCount: list.length,
                  separatorBuilder: (_, index) => const SizedBox(height: 10),
                  itemBuilder: (context, index) {
                    final item = list[index];
                    return _HistoryTile(
                      item: item,
                      onTap: () => _openConversation(context, ref, item.id),
                      onDelete: () => _deleteOne(context, ref, item.id),
                    );
                  },
                ),
        ),
      ),
    );
  }

  Future<void> _openConversation(
    BuildContext context,
    WidgetRef ref,
    String id,
  ) async {
    final error = await ref.read(chatProvider.notifier).loadConversation(id);
    if (error != null) {
      if (context.mounted) {
        AppToast.show(context, error, type: AppToastType.error);
      }
      return;
    }
    popRoute(ref);
  }

  Future<void> _deleteOne(
    BuildContext context,
    WidgetRef ref,
    String id,
  ) async {
    try {
      await ref.read(conversationHistoryProvider.notifier).deleteOne(id);
      if (context.mounted) {
        AppToast.show(context, '已删除', type: AppToastType.success);
      }
    } catch (_) {
      if (context.mounted) {
        AppToast.show(context, '删除失败，请稍后重试', type: AppToastType.error);
      }
    }
  }

  Future<void> _confirmClearAll(BuildContext context, WidgetRef ref) async {
    final ok = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('清空全部历史'),
        content: const Text('清空后无法恢复，确认继续？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(ctx, true),
            style: TextButton.styleFrom(foregroundColor: AppColors.error),
            child: const Text('清空'),
          ),
        ],
      ),
    );
    if (ok != true) return;
    try {
      final count = await ref
          .read(conversationHistoryProvider.notifier)
          .clearAll();
      if (context.mounted) {
        AppToast.show(context, '已清空 $count 条对话', type: AppToastType.success);
      }
    } catch (_) {
      if (context.mounted) {
        AppToast.show(context, '清空失败，请稍后重试', type: AppToastType.error);
      }
    }
  }
}

class _HistoryTile extends StatelessWidget {
  final ConversationListItem item;
  final VoidCallback onTap;
  final VoidCallback onDelete;

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

  @override
  Widget build(BuildContext context) {
    return Dismissible(
      key: ValueKey(item.id),
      direction: DismissDirection.endToStart,
      background: Container(
        alignment: Alignment.centerRight,
        padding: const EdgeInsets.only(right: 18),
        decoration: BoxDecoration(
          color: AppColors.error,
          borderRadius: BorderRadius.circular(14),
        ),
        child: const Icon(Icons.delete_outline, color: Colors.white),
      ),
      confirmDismiss: (_) async {
        onDelete();
        return true;
      },
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(14),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(14),
            border: Border.all(color: AppColors.borderLight),
            boxShadow: AppColors.cardShadowLight,
          ),
          child: Row(
            children: [
              Expanded(
                child: Text(
                  _displaySummary(item),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w800,
                    color: AppColors.textPrimary,
                  ),
                ),
              ),
              const SizedBox(width: 12),
              Text(
                _shortDate(item.updatedAt),
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w700,
                  color: AppColors.textHint,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  static String _displaySummary(ConversationListItem item) {
    final s = item.summary?.trim();
    if (s != null && s.isNotEmpty) return s.replaceAll(RegExp(r'\s+'), ' ');
    final t = item.title?.trim();
    if (t != null && t.isNotEmpty) return t.replaceAll(RegExp(r'\s+'), ' ');
    return '未命名对话';
  }

  static String _shortDate(DateTime time) {
    final now = DateTime.now();
    final local = time.toLocal();
    if (local.year == now.year &&
        local.month == now.month &&
        local.day == now.day) {
      return '今天';
    }
    final yesterday = now.subtract(const Duration(days: 1));
    if (local.year == yesterday.year &&
        local.month == yesterday.month &&
        local.day == yesterday.day) {
      return '昨天';
    }
    return '${local.month}/${local.day}';
  }
}

class _EmptyHint extends StatelessWidget {
  const _EmptyHint();

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: const [
        SizedBox(height: 120),
        Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(Icons.forum_outlined, size: 56, color: AppColors.textHint),
              SizedBox(height: 14),
              Text(
                '暂无历史对话',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w700,
                  color: AppColors.textPrimary,
                ),
              ),
              SizedBox(height: 6),
              Text(
                '在首页和 AI 健康助手聊天后会显示在这里',
                style: TextStyle(fontSize: 13, color: AppColors.textSecondary),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

class _ErrorBlock extends StatelessWidget {
  final String message;
  final VoidCallback onRetry;

  const _ErrorBlock({required this.message, required this.onRetry});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Icon(
            Icons.wifi_off_rounded,
            size: 56,
            color: AppColors.textHint,
          ),
          const SizedBox(height: 12),
          Text(message, style: const TextStyle(color: AppColors.textSecondary)),
          const SizedBox(height: 14),
          OutlinedButton(onPressed: onRetry, child: const Text('重试')),
        ],
      ),
    );
  }
}
