import React, { useState, useEffect } from "react";
import { getImageUrl } from "../services/uploadService";

interface AvatarUser {
  id?: string;
  firstName: string;
  lastName: string;
  imageFilename?: string;
}

interface AvatarProps {
  user: AvatarUser | null;
  size?: "xs" | "sm" | "md" | "lg" | "xl" | "xxl" | "xxxl";
  sizePx?: number;
  className?: string;
  onClick?: () => void;
  imageUrl?: string | null;
}

const sizeMap: Record<string, number> = {
  xs: 30,
  sm: 32,
  md: 35,
  lg: 50,
  xl: 60,
  xxl: 120,
  xxxl: 150,
};

const colors = [
  "#6366f1", // Indigo
  "#8b5cf6", // Violet
  "#ec4899", // Pink
  "#ef4444", // Red
  "#f97316", // Orange
  "#eab308", // Yellow
  "#22c55e", // Green
  "#14b8a6", // Teal
  "#06b6d4", // Cyan
  "#3b82f6", // Blue
];

const getAvatarColor = (
  firstName: string,
  lastName: string,
  userId?: string
): string => {
  const input = userId || `${firstName}${lastName}`;
  let hash = 0;
  for (let i = 0; i < input.length; i++) {
    hash = input.charCodeAt(i) + ((hash << 5) - hash);
  }
  return colors[Math.abs(hash) % colors.length];
};

const getInitials = (firstName: string, lastName: string): string => {
  const firstInitial = firstName?.charAt(0)?.toUpperCase() || "";
  const lastInitial = lastName?.charAt(0)?.toUpperCase() || "";
  return `${firstInitial}${lastInitial}` || "?";
};

const Avatar: React.FC<AvatarProps> = ({
  user,
  size = "md",
  sizePx,
  className = "",
  onClick,
  imageUrl: directImageUrl,
}) => {
  const [imageError, setImageError] = useState(false);

  // Reset error state when image URL changes
  useEffect(() => {
    setImageError(false);
  }, [directImageUrl, user?.imageFilename]);

  const pixelSize = sizePx || sizeMap[size];
  const fontSize = Math.max(pixelSize * 0.4, 12);

  // Handle missing user - show generic placeholder
  if (!user) {
    return (
      <div
        className={`rounded-circle bg-secondary d-flex align-items-center justify-content-center text-white ${className}`}
        style={{
          width: pixelSize,
          height: pixelSize,
          fontSize: fontSize,
          cursor: onClick ? "pointer" : "default",
        }}
        onClick={onClick}
        role="img"
        aria-label="User avatar"
      >
        <i className="bi bi-person-fill"></i>
      </div>
    );
  }

  const { firstName, lastName, imageFilename, id } = user;
  // Use direct imageUrl if provided, otherwise construct from imageFilename (use thumbnail for avatars)
  const imageUrl = directImageUrl || (imageFilename ? getImageUrl(imageFilename, 'thumbnail') : null);
  const hasValidImage = imageUrl && !imageError;

  if (hasValidImage) {
    return (
      <img
        src={imageUrl}
        alt={`${firstName} ${lastName}`}
        className={`rounded-circle ${className}`}
        style={{
          width: pixelSize,
          height: pixelSize,
          objectFit: "cover",
          cursor: onClick ? "pointer" : "default",
        }}
        onClick={onClick}
        onError={() => setImageError(true)}
      />
    );
  }

  // Initials fallback
  const bgColor = getAvatarColor(firstName, lastName, id);
  const initials = getInitials(firstName, lastName);

  return (
    <div
      className={`rounded-circle d-flex align-items-center justify-content-center text-white fw-bold ${className}`}
      style={{
        width: pixelSize,
        height: pixelSize,
        backgroundColor: bgColor,
        fontSize: fontSize,
        cursor: onClick ? "pointer" : "default",
      }}
      onClick={onClick}
      role="img"
      aria-label={`${firstName} ${lastName}'s avatar`}
    >
      {initials}
    </div>
  );
};

export default Avatar;
