/**
 * @ai-summary Vehicle image upload component with preview and validation
 */

import React, { useState, useRef, ChangeEvent } from 'react';
import { Box, Button, CircularProgress, IconButton, Typography } from '@mui/material';
import CloudUploadIcon from '@mui/icons-material/CloudUpload';
import DeleteIcon from '@mui/icons-material/Delete';
import { Vehicle } from '../types/vehicles.types';
import { VehicleImage } from './VehicleImage';

interface VehicleImageUploadProps {
  vehicle: Vehicle;
  onUpload: (file: File) => Promise<void>;
  onRemove: () => Promise<void>;
  disabled?: boolean;
}

const MAX_FILE_SIZE = 5 * 1024 * 1024;
const ALLOWED_TYPES = ['image/jpeg', 'image/png'];

export const VehicleImageUpload: React.FC<VehicleImageUploadProps> = ({
  vehicle,
  onUpload,
  onRemove,
  disabled = false
}) => {
  const [uploading, setUploading] = useState(false);
  const [removing, setRemoving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const handleFileSelect = async (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setError(null);

    if (!ALLOWED_TYPES.includes(file.type)) {
      setError('Please select a JPEG or PNG image');
      return;
    }

    if (file.size > MAX_FILE_SIZE) {
      setError('Image must be less than 5MB');
      return;
    }

    setUploading(true);
    try {
      await onUpload(file);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Upload failed');
    } finally {
      setUploading(false);
      if (inputRef.current) {
        inputRef.current.value = '';
      }
    }
  };

  const handleRemove = async () => {
    setError(null);
    setRemoving(true);
    try {
      await onRemove();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to remove image');
    } finally {
      setRemoving(false);
    }
  };

  const hasImage = !!vehicle.imageUrl;

  return (
    <Box>
      <Box sx={{ position: 'relative' }}>
        <VehicleImage vehicle={vehicle} height={120} />

        {(uploading || removing) && (
          <Box
            sx={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 16,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              bgcolor: 'rgba(0,0,0,0.5)',
              borderRadius: 2
            }}
          >
            <CircularProgress size={32} sx={{ color: 'white' }} />
          </Box>
        )}
      </Box>

      <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
        <input
          ref={inputRef}
          type="file"
          accept="image/jpeg,image/png"
          onChange={handleFileSelect}
          style={{ display: 'none' }}
          disabled={disabled || uploading || removing}
        />

        <Button
          variant="outlined"
          size="small"
          startIcon={<CloudUploadIcon />}
          onClick={() => inputRef.current?.click()}
          disabled={disabled || uploading || removing}
        >
          {hasImage ? 'Change Photo' : 'Add Photo'}
        </Button>

        {hasImage && (
          <IconButton
            size="small"
            onClick={handleRemove}
            disabled={disabled || uploading || removing}
            sx={{ color: 'error.main' }}
          >
            <DeleteIcon fontSize="small" />
          </IconButton>
        )}
      </Box>

      {error && (
        <Typography variant="caption" color="error" sx={{ display: 'block', mt: 1 }}>
          {error}
        </Typography>
      )}

      <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 0.5 }}>
        JPEG or PNG, max 5MB
      </Typography>
    </Box>
  );
};
