"use client";

import Image from "next/image";
import { useState, useEffect } from "react";

interface S3ImageProps {
  s3Key: string | null;
  alt: string;
  className?: string;
  width?: number;
  height?: number;
  fill?: boolean;
  priority?: boolean;
  fallbackSrc?: string;
}

/**
 * S3Image Component
 * Automatically handles S3 signed URLs, local paths, and fallbacks
 * Supports both S3 keys and backward compatibility with local uploads
 */
export default function S3Image({
  s3Key,
  alt,
  className,
  width,
  height,
  fill,
  priority,
  fallbackSrc = "/placeholder.jpg",
}: S3ImageProps) {
  const [signedUrl, setSignedUrl] = useState<string | null>(null);
  const [error, setError] = useState(false);

  useEffect(() => {
    if (!s3Key) {
      setError(true);
      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;
    }

    // Fetch signed URL for S3 key
    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]);

  const src = error ? fallbackSrc : (signedUrl || fallbackSrc);

  if (fill) {
    return (
      <Image
        src={src}
        alt={alt}
        fill
        className={className}
        priority={priority}
        onError={() => setError(true)}
      />
    );
  }

  return (
    <Image
      src={src}
      alt={alt}
      width={width || 400}
      height={height || 300}
      className={className}
      priority={priority}
      onError={() => setError(true)}
    />
  );
}
