import 'package:flutter/material.dart';
import 'package:on_field_work/helpers/widgets/my_container.dart';
import 'package:on_field_work/helpers/widgets/my_text.dart';

class Avatar extends StatelessWidget {
  final String firstName;
  final String lastName;
  final String? imageUrl;
  final double size;
  final Color? backgroundColor;
  final Color textColor;

  const Avatar({
    super.key,
    required this.firstName,
    required this.lastName,
    this.imageUrl,
    this.size = 46.0,
    this.backgroundColor,
    this.textColor = Colors.white,
  });

  @override
  Widget build(BuildContext context) {
    if (imageUrl != null && imageUrl!.isNotEmpty) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(size / 2),
        child: Image.network(
          imageUrl!,
          width: size,
          height: size,
          fit: BoxFit.cover,
        ),
      );
    }

    String initials =
        "${firstName.isNotEmpty ? firstName[0] : ''}${lastName.isNotEmpty ? lastName[0] : ''}"
            .toUpperCase();

    final Color bgColor =
        backgroundColor ?? _getFlatColorFromName('$firstName$lastName');

    return MyContainer.rounded(
      height: size,
      width: size,
      paddingAll: 0,
      color: bgColor,
      child: Center(
        child: MyText(
          initials,
          fontSize: size * 0.45,
          fontWeight: 600,
          color: textColor,
        ),
      ),
    );
  }
}

// Use fixed flat color palette and pick based on hash
Color _getFlatColorFromName(String name) {
  final colors = <Color>[
    Color(0xFFE57373), // Red
    Color(0xFFF06292), // Pink
    Color(0xFFBA68C8), // Purple
    Color(0xFF9575CD), // Deep Purple
    Color(0xFF7986CB), // Indigo
    Color(0xFF64B5F6), // Blue
    Color(0xFF4FC3F7), // Light Blue
    Color(0xFF4DD0E1), // Cyan
    Color(0xFF4DB6AC), // Teal
    Color(0xFF81C784), // Green
    Color(0xFFAED581), // Light Green
    Color(0xFFDCE775), // Lime
    Color(0xFFFFD54F), // Amber
    Color(0xFFFFB74D), // Orange
    Color(0xFFA1887F), // Brown
    Color(0xFF90A4AE), // Blue Grey
  ];

  int index = name.hashCode.abs() % colors.length;
  return colors[index];
}
