import { useState, useEffect } from 'react';

/**
 * Hook to fetch signed URL for S3 keys
 * Handles local paths, full URLs, and S3 keys automatically
 * @param imageKey - S3 key, local path, or full URL
 * @returns Display URL (either the original URL or a signed URL for S3 keys)
 */
export function useS3Image(imageKey: string | null | undefined): string | null {
  const [displayUrl, setDisplayUrl] = useState<string | null>(null);

  useEffect(() => {
    if (!imageKey) {
      // Use setTimeout to avoid synchronous setState
      const timer = setTimeout(() => setDisplayUrl(null), 0);
      return () => clearTimeout(timer);
    }

    // If it's a local path or full URL, use it directly
    if (imageKey.startsWith('/') || imageKey.startsWith('http')) {
      // Use setTimeout to avoid synchronous setState in effect
      const timer = setTimeout(() => setDisplayUrl(imageKey), 0);
      return () => clearTimeout(timer);
    }

    // If it's an S3 key, fetch signed URL
    if (imageKey.startsWith('avatars/') || imageKey.startsWith('tours/')) {
      let isMounted = true;
      
      const fetchSignedUrl = async () => {
        try {
          const response = await fetch(
            `/api/images/signed-url?key=${encodeURIComponent(imageKey)}`
          );
          
          if (response.ok && isMounted) {
            const data = await response.json();
            setDisplayUrl(data.url);
          }
        } catch (error) {
          console.error('Error fetching signed URL for:', imageKey, error);
        }
      };

      fetchSignedUrl();

      return () => {
        isMounted = false;
      };
    }
  }, [imageKey]);

  return displayUrl;
}
