import 'package:flutter/material.dart';
import '../../../core/theme/design_tokens.dart';

enum MessageSender { user, ai }

class ChatBubble extends StatelessWidget {
  final MessageSender sender;
  final String content;
  final DateTime timestamp;
  final bool showTimestamp;
  final Widget? extraContent;

  const ChatBubble({
    super.key,
    required this.sender,
    required this.content,
    required this.timestamp,
    this.showTimestamp = true,
    this.extraContent,
  });

  @override
  Widget build(BuildContext context) {
    final isUser = sender == MessageSender.user;

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 6),
      child: Column(
        crossAxisAlignment: isUser
            ? CrossAxisAlignment.end
            : CrossAxisAlignment.start,
        children: [
          if (showTimestamp)
            Padding(
              padding: const EdgeInsets.only(bottom: 6),
              child: Text(
                _formatTimestamp(timestamp),
                style: const TextStyle(fontSize: 11, color: AppColors.slate400),
              ),
            ),
          Container(
            constraints: BoxConstraints(
              maxWidth: MediaQuery.of(context).size.width * 0.82,
            ),
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            decoration: BoxDecoration(
              color: isUser ? AppColors.blue500 : AppColors.white,
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.06),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: content.isNotEmpty
                ? Text(
                    content,
                    style: TextStyle(
                      fontSize: 15,
                      color: isUser ? AppColors.white : AppColors.slate700,
                      height: 1.45,
                    ),
                  )
                : (extraContent ?? const SizedBox.shrink()),
          ),
        ],
      ),
    );
  }

  String _formatTimestamp(DateTime time) {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    final msgDate = DateTime(time.year, time.month, time.day);

    String dateStr;
    if (msgDate == today) {
      dateStr = '今天';
    } else if (msgDate == today.subtract(const Duration(days: 1))) {
      dateStr = '昨天';
    } else {
      dateStr = '${time.month}月${time.day}日';
    }

    final timeStr =
        '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
    return '$dateStr $timeStr';
  }
}
