'use client'

import { useState, useEffect } from 'react'
import { cn, getInitials } from '@/lib/utils'
import { ClipboardList } from 'lucide-react'
import {
  Dialog,
  DialogContent,
  DialogTitle,
} from '@/components/ui/dialog'
import { VisuallyHidden } from '@radix-ui/react-visually-hidden'

type ProjectLogoProps = {
  project: {
    title: string
    logoKey?: string | null
  }
  logoUrl?: string | null
  size?: 'sm' | 'md' | 'lg'
  fallback?: 'icon' | 'initials'
  className?: string
  /** When true, clicking the logo opens a lightbox */
  clickToEnlarge?: boolean
}

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,
  clickToEnlarge,
}: ProjectLogoProps) {
  const [imageError, setImageError] = useState(false)
  const [lightboxOpen, setLightboxOpen] = useState(false)
  const initials = getInitials(project.title)

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

  const showImage = logoUrl && !imageError
  const canEnlarge = clickToEnlarge && showImage

  const logoElement = showImage ? (
    <div
      className={cn(
        'relative overflow-hidden rounded-lg bg-muted',
        sizeClasses[size],
        canEnlarge && 'cursor-pointer ring-offset-background transition-all hover:ring-2 hover:ring-primary/30',
        className
      )}
      onClick={canEnlarge ? () => setLightboxOpen(true) : undefined}
    >
      <img
        src={logoUrl}
        alt={`${project.title} logo`}
        className="h-full w-full object-cover"
        onError={() => setImageError(true)}
      />
    </div>
  ) : (
    <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>
  )

  return (
    <>
      {logoElement}
      {canEnlarge && (
        <Dialog open={lightboxOpen} onOpenChange={setLightboxOpen}>
          <DialogContent className="max-w-lg p-2">
            <VisuallyHidden><DialogTitle>{project.title} logo</DialogTitle></VisuallyHidden>
            <img
              src={logoUrl!}
              alt={`${project.title} logo`}
              className="w-full rounded-lg object-contain"
            />
          </DialogContent>
        </Dialog>
      )}
    </>
  )
}
