import 'package:flutter/material.dart';

import '../../../../api/marianumconnect/queries/user_search/user_search_response.dart';
import '../../../../widget/user_avatar.dart';

/// List entry for a MarianumConnect user-search hit: avatar, full name, a muted
/// identifier line and a colour-coded role badge. Shared by the dedicated user
/// search ([JoinChat]) and the "start new chat" section of the chat search.
class UserSearchTile extends StatelessWidget {
  final McUserSearchResult user;
  final VoidCallback onTap;

  const UserSearchTile({super.key, required this.user, required this.onTap});

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: UserAvatar(id: user.username, isGroup: false),
      title: Text('${user.firstName} ${user.lastName}'),
      subtitle: Text(_subtitle),
      trailing: RoleBadge(userType: user.userType),
      onTap: onTap,
    );
  }

  String get _subtitle {
    final className = user.className;
    if (user.userType == 'STUDENT' &&
        className != null &&
        className.isNotEmpty) {
      return '${user.username} · $className';
    }
    return user.username;
  }
}

/// Compact colour-coded badge distinguishing teachers, students and staff.
class RoleBadge extends StatelessWidget {
  final String userType;

  const RoleBadge({super.key, required this.userType});

  @override
  Widget build(BuildContext context) {
    final (label, color) = switch (userType) {
      'TEACHER' => ('Lehrkraft', Colors.blue),
      'STUDENT' => ('Schüler:in', Colors.green),
      _ => ('Personal', Colors.orange),
    };
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withValues(alpha: 0.15),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Text(
        label,
        style: TextStyle(
          color: color,
          fontSize: 12,
          fontWeight: FontWeight.w600,
        ),
      ),
    );
  }
}
