import React, { memo } from 'react';
import { FormControl, InputLabel, Select, MenuItem, FormHelperText, Box, Typography } from '@mui/material';
import DirectionsCarIcon from '@mui/icons-material/DirectionsCar';
import { useVehicles } from '../../vehicles/hooks/useVehicles';
import type { Vehicle } from '../../vehicles/types/vehicles.types';

interface Props {
  value?: string;
  onChange: (vehicleId: string) => void;
  error?: string;
  required?: boolean;
  disabled?: boolean;
}

const VehicleSelectorComponent: React.FC<Props> = ({ value, onChange, error, required, disabled }) => {
  const { data: vehicles, isLoading } = useVehicles();

  // DEBUG: Log vehicle selector renders and data changes
  console.log('[VehicleSelector] Render - value:', value, 'vehicles count:', Array.isArray(vehicles) ? vehicles.length : 0, 'isLoading:', isLoading);

  if (!isLoading && (!vehicles || vehicles.length === 0)) {
    return (
      <Box p={2} borderRadius={1} bgcolor={'background.default'}>
        <Typography variant="body2" color="text.secondary">
          You need to add a vehicle before creating fuel logs.
        </Typography>
      </Box>
    );
  }

  return (
    <FormControl fullWidth error={!!error} required={required}>
      <InputLabel>Select Vehicle</InputLabel>
      <Select value={value || ''} onChange={(e) => onChange(e.target.value as string)} label="Select Vehicle" disabled={disabled}>
        {vehicles && Array.isArray(vehicles) ? vehicles.map((v: Vehicle) => (
          <MenuItem key={v.id} value={v.id}>
            <Box display="flex" alignItems="center" gap={1}>
              <DirectionsCarIcon fontSize="small" />
              <Typography variant="body2">{`${v.year || ''} ${v.make || ''} ${v.model || ''}`.trim()}</Typography>
            </Box>
          </MenuItem>
        )) : null}
      </Select>
      {error && <FormHelperText>{error}</FormHelperText>}
    </FormControl>
  );
};

export const VehicleSelector = memo(VehicleSelectorComponent);
