import 'package:flutter/material.dart';
import '../../core/app_colors.dart';
import '../screens/chat_screen.dart';
import '/data/models/contact_model.dart';

class ContactTile extends StatelessWidget {
  final Contact contact;
  final VoidCallback? onTap;

  const ContactTile({super.key, required this.contact, this.onTap});

  @override
  Widget build(BuildContext context) {
    final primary = Theme.of(context).colorScheme.primary;

    return ListTile(
      onTap: onTap,
      contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      leading: CircleAvatar(
        radius: 28,
        backgroundColor: primary.withAlpha((0.1 * 255).round()),
        child: Text(
          contact.surname[0],
          style: TextStyle(color: Theme.of(context).colorScheme.primary, fontWeight: FontWeight.bold)
        ),
      ),
      title: Text(
        contact.username,
        style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
      ),
      subtitle: Text(
        contact.lastMessage ?? "Нет сообщений",
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: const TextStyle(color: AppColors.textSecondary),
      ),
      trailing: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: [
          Text(
            _formatTime(contact.lastMessageTime),
            style: const TextStyle(color: AppColors.textSecondary, fontSize: 12),
          ),
          const SizedBox(height: 4),
          if (contact.unreadCount > 0)
            Container(
              padding: const EdgeInsets.all(6),
              decoration: BoxDecoration(color: primary.withAlpha((0.5 * 255).round()), shape: BoxShape.circle),
              child: Text(
                '${contact.unreadCount}',
                style: const TextStyle(color: Colors.white, fontSize: 10),
              ),
            ),
        ],
      ),
    );
  }

  String _formatTime(DateTime? time) {
    if (time == null) return "";
    return "${time.hour}:${time.minute.toString().padLeft(2, '0')}";
  }
}