/**
 * @ai-summary Authenticated station photo loader using backend proxy
 */

import React, { useEffect, useState } from 'react';
import { CardMedia, CircularProgress, Box } from '@mui/material';
import { apiClient } from '@/core/api/client';
import { getStationPhotoUrl } from '../utils/photo-utils';

interface StationPhotoProps {
  photoReference?: string;
  alt: string;
  height?: number | string;
}

export const StationPhoto: React.FC<StationPhotoProps> = ({ photoReference, alt, height = 200 }) => {
  const [photoUrl, setPhotoUrl] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    let isMounted = true;
    let objectUrl: string | null = null;

    const loadPhoto = async () => {
      if (!photoReference) {
        setPhotoUrl(null);
        return;
      }

      setIsLoading(true);

      try {
        const url = getStationPhotoUrl(photoReference);
        if (!url) {
          setPhotoUrl(null);
          return;
        }

        const response = await apiClient.get(url, {
          responseType: 'blob'
        });

        objectUrl = URL.createObjectURL(response.data);

        if (isMounted) {
          setPhotoUrl(objectUrl);
        }
      } catch (error) {
        // Silent fail – just hide the image if the request is unauthorized or fails
        if (isMounted) {
          setPhotoUrl(null);
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    };

    loadPhoto();

    return () => {
      isMounted = false;
      if (objectUrl) {
        URL.revokeObjectURL(objectUrl);
      }
    };
  }, [photoReference]);

  if (!photoReference) {
    return null;
  }

  if (isLoading && !photoUrl) {
    return (
      <Box
        sx={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          height
        }}
        data-testid="station-photo-loading"
      >
        <CircularProgress size={24} />
      </Box>
    );
  }

  if (!photoUrl) {
    return null;
  }

  return (
    <CardMedia
      component="img"
      height={height}
      image={photoUrl}
      alt={alt}
      sx={{ objectFit: 'cover' }}
    />
  );
};

export default StationPhoto;
