"use client";

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useState, useEffect } from "react";

interface S3AvatarProps {
  s3Key: string | null | undefined;
  fallback: string;
  alt?: string;
  className?: string;
}

/**
 * S3Avatar Component
 * Automatically handles S3 signed URLs for avatar images
 * Supports both S3 keys and backward compatibility with local paths
 */
export default function S3Avatar({
  s3Key,
  fallback,
  alt = "User",
  className,
}: S3AvatarProps) {
  const [signedUrl, setSignedUrl] = useState<string | null>(null);
  const [error, setError] = useState(false);

  useEffect(() => {
    if (!s3Key) {
      return;
    }

    // Check if it's already a full URL (backward compatibility)
    if (s3Key.startsWith("http")) {
      setSignedUrl(s3Key);
      return;
    }

    // Check if it's a local path (backward compatibility)
    if (s3Key.startsWith("/uploads/")) {
      setSignedUrl(s3Key);
      return;
    }

    // It's an S3 key - fetch signed URL
    const fetchSignedUrl = async () => {
      try {
        const response = await fetch(
          `/api/images/signed-url?key=${encodeURIComponent(s3Key)}`
        );
        
        if (!response.ok) {
          throw new Error("Failed to get signed URL");
        }

        const data = await response.json();
        setSignedUrl(data.url);
      } catch (err) {
        console.error("Error fetching signed URL:", err);
        setError(true);
      }
    };

    fetchSignedUrl();
  }, [s3Key]);

  return (
    <Avatar className={className}>
      <AvatarImage 
        src={error ? undefined : (signedUrl || undefined)} 
        alt={alt}
      />
      <AvatarFallback>{fallback}</AvatarFallback>
    </Avatar>
  );
}
