'use client';

import { Camera, Loader2 } from 'lucide-react';
import { useId } from 'react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { useResilientBlobUrl } from '@/hooks/use-resilient-blob-url';
import { cn } from '@/lib/utils';

interface HoverUploadAvatarProps {
  name: string;
  imageUrl?: string | null;
  imageToken?: string | null;
  uploading?: boolean;
  onFileSelect: (file: File) => void;
  className?: string;
  fallbackClassName?: string;
}

export function HoverUploadAvatar({
  name,
  imageUrl,
  imageToken = null,
  uploading = false,
  onFileSelect,
  className,
  fallbackClassName
}: HoverUploadAvatarProps) {
  const inputId = useId();
  const { blobUrl, isLoading } = useResilientBlobUrl(imageUrl, imageToken, {
    enabled: Boolean(imageUrl && imageToken),
    label: `аватар ${name}`
  });
  const resolvedUrl = blobUrl ?? (imageToken ? null : imageUrl);

  return (
    <label
      htmlFor={inputId}
      className={cn(
        'group/avatar relative block cursor-pointer overflow-hidden rounded-full transition',
        uploading && 'pointer-events-none',
        className
      )}
    >
      <Avatar className="h-full w-full">
        {isLoading && imageUrl ? (
          <AvatarFallback className="bg-transparent p-0">
            <Skeleton className="h-full w-full rounded-full" />
          </AvatarFallback>
        ) : (
          <>
            {resolvedUrl ? <AvatarImage src={resolvedUrl} alt={name} /> : null}
            <AvatarFallback className={fallbackClassName}>{name.slice(0, 2).toUpperCase()}</AvatarFallback>
          </>
        )}
      </Avatar>
      <span
        className={cn(
          'absolute inset-0 flex items-center justify-center bg-black/45 text-white opacity-0 transition-opacity duration-200 group-hover/avatar:opacity-100',
          uploading && 'opacity-100'
        )}
      >
        {uploading ? <Loader2 className="h-5 w-5 animate-spin" /> : <Camera className="h-5 w-5" />}
      </span>
      <input
        id={inputId}
        type="file"
        accept="image/*"
        className="sr-only"
        disabled={uploading}
        onChange={(event) => {
          const file = event.target.files?.[0];
          if (file) onFileSelect(file);
          event.target.value = '';
        }}
      />
    </label>
  );
}
