import { Link } from "wouter";
import { Author } from "@shared/schema";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";

interface AuthorChipProps {
  author?: Author;
  size?: 'sm' | 'md' | 'lg';
  withLifeDates?: boolean;
  className?: string;
}

export function AuthorChip({ author, size = 'md', withLifeDates = false, className = '' }: AuthorChipProps) {
  // Helper function to get avatar size class
  function getAvatarSize() {
    switch (size) {
      case 'sm': return 'w-8 h-8';
      case 'lg': return 'w-12 h-12';
      default: return 'w-10 h-10';
    }
  }

  // Helper function to get text size class
  function getTextSize() {
    switch (size) {
      case 'sm': return 'text-sm';
      case 'lg': return 'text-lg';
      default: return 'text-base';
    }
  }

  // Get initials for avatar fallback
  function getInitials(name: string) {
    return name
      .split(' ')
      .map(part => part.charAt(0))
      .join('')
      .toUpperCase()
      .slice(0, 2);
  }

  // If author is undefined, return a placeholder
  if (!author) {
    return (
      <div className={`flex items-center gap-2 ${className}`}>
        <div className={`flex items-center justify-center rounded-full bg-navy/10 dark:bg-navy/20 overflow-hidden flex-shrink-0 ${getAvatarSize()}`}>
          <span className="text-navy/60 dark:text-cream/60">?</span>
        </div>
        <div>
          <h3 className={`${getTextSize()} text-navy/70 dark:text-cream/70 font-medium`}>
            Unknown Author
          </h3>
        </div>
      </div>
    );
  }

  // If author is defined, return the full component
  return (
    <Link href={`/authors/${author.slug}`}>
      <div className={`flex items-center gap-2 group ${className}`}>
        <Avatar className={`rounded-full bg-navy/10 dark:bg-navy/20 overflow-hidden flex-shrink-0 ${getAvatarSize()}`}>
          <AvatarImage src={author.portrait || ''} alt={author.name} />
          <AvatarFallback className="bg-navy/10 dark:bg-navy/20 text-navy dark:text-cream">
            {getInitials(author.name)}
          </AvatarFallback>
        </Avatar>
        <div>
          <h3 className={`${getTextSize()} text-navy dark:text-cream font-medium group-hover:text-russet dark:group-hover:text-russet/90 transition-colors`}>
            {author.name}
          </h3>
          {withLifeDates && author.birthYear && (
            <p className="text-xs text-navy/70 dark:text-cream/70">
              {author.birthYear}–{author.deathYear || 'present'}
            </p>
          )}
        </div>
      </div>
    </Link>
  );
}
