import React, { useEffect } from 'react';
import { FormControl, InputLabel, Select, MenuItem, Grid, FormHelperText } from '@mui/material';
import { FuelType, FuelGrade } from '../types/fuel-logs.types';
import { useFuelGrades } from '../hooks/useFuelGrades';

interface Props {
  fuelType: FuelType;
  fuelGrade?: FuelGrade;
  onFuelTypeChange: (fuelType: FuelType) => void;
  onFuelGradeChange: (fuelGrade?: FuelGrade) => void;
  error?: string;
  disabled?: boolean;
}

export const FuelTypeSelector: React.FC<Props> = ({ fuelType, fuelGrade, onFuelTypeChange, onFuelGradeChange, error, disabled }) => {
  const { fuelGrades, isLoading } = useFuelGrades(fuelType);

  useEffect(() => {
    if (fuelGrade && fuelGrades && !fuelGrades.some(g => g.value === fuelGrade)) {
      onFuelGradeChange(undefined);
    }
  }, [fuelType, fuelGrades, fuelGrade, onFuelGradeChange]);

  useEffect(() => {
    if (!fuelGrade && fuelGrades && fuelGrades.length > 0) {
      onFuelGradeChange(fuelGrades[0].value as FuelGrade);
    }
  }, [fuelGrades, fuelGrade, onFuelGradeChange]);

  return (
    <Grid container spacing={2}>
      <Grid item xs={12} sm={6}>
        <FormControl fullWidth error={!!error}>
          <InputLabel>Fuel Type</InputLabel>
          <Select value={fuelType} label="Fuel Type" onChange={(e) => onFuelTypeChange(e.target.value as FuelType)} disabled={disabled}>
            <MenuItem value={FuelType.GASOLINE}>Gasoline</MenuItem>
            <MenuItem value={FuelType.DIESEL}>Diesel</MenuItem>
            <MenuItem value={FuelType.ELECTRIC}>Electric</MenuItem>
          </Select>
          {error && <FormHelperText>{error}</FormHelperText>}
        </FormControl>
      </Grid>
      <Grid item xs={12} sm={6}>
        <FormControl fullWidth disabled={disabled || isLoading || fuelType === FuelType.ELECTRIC}>
          <InputLabel>Fuel Grade</InputLabel>
          <Select value={fuelGrade || ''} label="Fuel Grade" onChange={(e) => onFuelGradeChange(e.target.value as FuelGrade)}>
            {fuelGrades?.map((g) => (
              <MenuItem key={g.value || 'none'} value={g.value || ''}>{g.label}</MenuItem>
            ))}
          </Select>
          {fuelType !== FuelType.ELECTRIC && <FormHelperText>{isLoading ? 'Loading grades…' : 'Select a grade'}</FormHelperText>}
        </FormControl>
      </Grid>
    </Grid>
  );
};

