'use client'

import { useState, useEffect } from 'react'
import { cn, getInitials } from '@/lib/utils'
import { ClipboardList } from 'lucide-react'

type ProjectLogoProps = {
  project: {
    title: string
    logoKey?: string | null
  }
  logoUrl?: string | null
  size?: 'sm' | 'md' | 'lg'
  fallback?: 'icon' | 'initials'
  className?: string
}

const sizeClasses = {
  sm: 'h-8 w-8',
  md: 'h-10 w-10',
  lg: 'h-16 w-16',
}

const iconSizeClasses = {
  sm: 'h-4 w-4',
  md: 'h-5 w-5',
  lg: 'h-8 w-8',
}

const textSizeClasses = {
  sm: 'text-xs',
  md: 'text-sm',
  lg: 'text-lg',
}

export function ProjectLogo({
  project,
  logoUrl,
  size = 'md',
  fallback = 'icon',
  className,
}: ProjectLogoProps) {
  const [imageError, setImageError] = useState(false)
  const initials = getInitials(project.title)

  // Reset error state when logoUrl changes
  useEffect(() => {
    setImageError(false)
  }, [logoUrl])

  const showImage = logoUrl && !imageError

  if (showImage) {
    return (
      <div
        className={cn(
          'relative overflow-hidden rounded-lg bg-muted',
          sizeClasses[size],
          className
        )}
      >
        <img
          src={logoUrl}
          alt={`${project.title} logo`}
          className="h-full w-full object-cover"
          onError={() => setImageError(true)}
        />
      </div>
    )
  }

  // Fallback
  return (
    <div
      className={cn(
        'flex items-center justify-center rounded-lg bg-muted',
        sizeClasses[size],
        className
      )}
    >
      {fallback === 'icon' ? (
        <ClipboardList className={cn('text-muted-foreground', iconSizeClasses[size])} />
      ) : (
        <span className={cn('font-medium text-muted-foreground', textSizeClasses[size])}>
          {initials}
        </span>
      )}
    </div>
  )
}
