/**
 * @ai-summary Vehicle image display with three-tier fallback
 * Tier 1: Custom uploaded image (fetched with auth headers)
 * Tier 2: Make logo from /images/makes/
 * Tier 3: Color box placeholder
 */

import React, { useState, useEffect } from 'react';
import { Box } from '@mui/material';
import { Vehicle } from '../types/vehicles.types';
import { apiClient } from '../../../core/api/client';

interface VehicleImageProps {
  vehicle: Vehicle;
  height?: number;
  borderRadius?: number;
}

const getMakeLogoPath = (make?: string): string | null => {
  if (!make) return null;
  const normalized = make.toLowerCase().replace(/\s+/g, '-');
  return `/images/makes/${normalized}.png`;
};

export const VehicleImage: React.FC<VehicleImageProps> = ({
  vehicle,
  height = 96,
  borderRadius = 2
}) => {
  const [imgError, setImgError] = useState(false);
  const [logoError, setLogoError] = useState(false);
  const [blobUrl, setBlobUrl] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(false);

  // Fetch authenticated image and create blob URL
  useEffect(() => {
    setImgError(false);
    setLogoError(false);

    if (!vehicle.imageUrl) {
      setBlobUrl(null);
      return;
    }

    // If imageUrl is already a blob URL (from preview), use it directly
    if (vehicle.imageUrl.startsWith('blob:')) {
      setBlobUrl(vehicle.imageUrl);
      return;
    }

    let cancelled = false;
    setIsLoading(true);

    // Strip /api prefix if present since apiClient adds it
    const url = vehicle.imageUrl.startsWith('/api/')
      ? vehicle.imageUrl.slice(4)
      : vehicle.imageUrl;

    apiClient.get(url, { responseType: 'blob' })
      .then(response => {
        if (cancelled) return;
        const blobUrl = URL.createObjectURL(response.data);
        setBlobUrl(blobUrl);
      })
      .catch(() => {
        if (cancelled) return;
        setImgError(true);
      })
      .finally(() => {
        if (!cancelled) setIsLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, [vehicle.id, vehicle.imageUrl]);

  // Clean up blob URL on unmount (only if we created it, not if it was passed in)
  useEffect(() => {
    return () => {
      if (blobUrl && vehicle.imageUrl !== blobUrl) {
        URL.revokeObjectURL(blobUrl);
      }
    };
  }, [blobUrl, vehicle.imageUrl]);

  if (vehicle.imageUrl && !imgError && (blobUrl || isLoading)) {
    return (
      <Box sx={{ height, borderRadius, overflow: 'hidden', mb: 2, bgcolor: isLoading ? 'action.hover' : undefined }}>
        {blobUrl && (
          <img
            src={blobUrl}
            alt={`${vehicle.make || ''} ${vehicle.model || ''}`.trim() || 'Vehicle'}
            style={{ width: '100%', height: '100%', objectFit: 'cover' }}
            onError={() => setImgError(true)}
          />
        )}
      </Box>
    );
  }

  const logoPath = getMakeLogoPath(vehicle.make);
  if (logoPath && !logoError) {
    return (
      <Box sx={{
        height,
        borderRadius,
        bgcolor: 'action.hover',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        p: 2,
        mb: 2
      }}>
        <img
          src={logoPath}
          alt={`${vehicle.make} logo`}
          style={{ maxHeight: '70%', maxWidth: '70%', objectFit: 'contain' }}
          onError={() => setLogoError(true)}
        />
      </Box>
    );
  }

  return (
    <Box
      sx={{
        height,
        bgcolor: vehicle.color || 'action.hover',
        borderRadius,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        mb: 2
      }}
    />
  );
};
