import '../models/ag_ui_event.dart';
import '../models/tool_result.dart';

class MockHistoryService {
  static final MockHistoryService _instance = MockHistoryService._internal();
  factory MockHistoryService() => _instance;
  MockHistoryService._internal();

  /// Normalize DateTime to date-only (midnight)
  DateTime _toDateOnly(DateTime date) =>
      DateTime(date.year, date.month, date.day);

  List<SnapshotMessage> getHistoryForDay(DateTime date) {
    final dayStart = _toDateOnly(date);
    final allHistory = _generateAllHistory();

    return allHistory.where((msg) {
      if (msg.timestamp == null) return false;
      final msgDate = _toDateOnly(msg.timestamp!);
      return msgDate == dayStart;
    }).toList();
  }

  DateTime? getLatestHistoryDate() {
    final allHistory = _generateAllHistory();
    if (allHistory.isEmpty) return null;

    return allHistory
        .where((msg) => msg.timestamp != null)
        .map((msg) => _toDateOnly(msg.timestamp!))
        .reduce((a, b) => a.isAfter(b) ? a : b);
  }

  DateTime? getPreviousDay(DateTime currentDate) {
    final allDates = _getAllHistoryDates();
    final sortedDates = allDates.toList()..sort((a, b) => b.compareTo(a));
    final currentDateOnly = _toDateOnly(currentDate);

    for (final date in sortedDates) {
      if (date.isBefore(currentDateOnly)) {
        return date;
      }
    }
    return null;
  }

  bool hasEarlierHistory(DateTime fromDate) {
    final allDates = _getAllHistoryDates();
    final fromDateOnly = _toDateOnly(fromDate);

    return allDates.any((date) => date.isBefore(fromDateOnly));
  }

  Set<DateTime> _getAllHistoryDates() {
    final now = DateTime.now();
    final today = _toDateOnly(now);
    final yesterday = today.subtract(const Duration(days: 1));
    return {today, yesterday};
  }

  List<SnapshotMessage> _generateAllHistory() {
    final now = DateTime.now();
    final today = _toDateOnly(now);
    final yesterday = today.subtract(const Duration(days: 1));

    return [
      SnapshotMessage(
        id: 'hist-m1',
        role: 'user',
        content: '明天提醒我开会',
        timestamp: today.add(const Duration(hours: 10)),
      ),
      SnapshotMessage(
        id: 'hist-t1',
        role: 'tool',
        toolCallId: 'hist-tc1',
        timestamp: today.add(const Duration(hours: 10)),
        ui: UiCard(
          cardType: 'calendar_card.v1',
          data: CalendarCardData(
            id: 'hist-s1',
            title: '产品评审会议',
            description: '讨论Q2产品路线图',
            startAt: today
                .add(const Duration(days: 1, hours: 10))
                .toIso8601String(),
            endAt: today
                .add(const Duration(days: 1, hours: 11))
                .toIso8601String(),
            timezone: 'Asia/Shanghai',
            location: '会议室A / 在线',
            color: '#4F46E5',
            sourceType: 'ai_generated',
          ).toJson(),
          actions: [
            CardAction(
              type: 'link',
              label: '查看详情',
              target: '/calendar/hist-s1',
            ),
          ],
        ),
      ),
      SnapshotMessage(
        id: 'hist-m2',
        role: 'assistant',
        content: '已为你创建日程"产品评审会议"，明天上午10:00。我还会提前15分钟提醒你。',
        timestamp: today.add(const Duration(hours: 10)),
      ),
      SnapshotMessage(
        id: 'hist-m3',
        role: 'user',
        content: '下周一之前提交项目报告',
        timestamp: yesterday.add(const Duration(hours: 14)),
      ),
      SnapshotMessage(
        id: 'hist-t2',
        role: 'tool',
        toolCallId: 'hist-tc2',
        timestamp: yesterday.add(const Duration(hours: 14)),
        ui: UiCard(
          cardType: 'calendar_card.v1',
          data: CalendarCardData(
            id: 'hist-s2',
            title: '提交项目报告',
            description: '完成并提交Q2项目报告',
            startAt: yesterday.add(const Duration(days: 5)).toIso8601String(),
            endAt: null,
            timezone: 'Asia/Shanghai',
            location: null,
            color: '#F59E0B',
            sourceType: 'ai_generated',
          ).toJson(),
          actions: [
            CardAction(
              type: 'link',
              label: '查看详情',
              target: '/calendar/hist-s2',
            ),
          ],
        ),
      ),
      SnapshotMessage(
        id: 'hist-m4',
        role: 'assistant',
        content: '好的，我已帮你创建待办事项"提交项目报告"，截止日期为下周一。我还会提醒你完成这项任务。',
        timestamp: yesterday.add(const Duration(hours: 14)),
      ),
      SnapshotMessage(
        id: 'hist-m5',
        role: 'assistant',
        content: '你好，我有什么可以帮你的？',
        timestamp: yesterday.add(const Duration(hours: 9)),
      ),
    ];
  }
}
