import { useMemo } from 'react';
import { useUnitPreferences } from '@/hooks/useUnitPreferences';
import { 
  convertValueFromMetric,
  getDisplayUnit,
  getSpeedUnit,
  getDistanceUnit,
  getHeightUnit,
  getShortDistanceUnit,
  type MeasurementSystem
} from '@/lib/units';

interface MeasurementDisplayProps {
  value: number;
  type: 'speed' | 'distance' | 'height' | 'short_distance';
  showBothUnits?: boolean;
  className?: string;
}

export function MeasurementDisplay({ 
  value, 
  type, 
  showBothUnits = false,
  className = "" 
}: MeasurementDisplayProps) {
  const { preferences: unitPreferences } = useUnitPreferences();

  const { displayValue, unit, alternateDisplay, tooltipText } = useMemo(() => {
    const system = unitPreferences.measurement_system;
    
    let metricUnit: string;
    let displayUnit: string;
    let alternateSystem: MeasurementSystem;
    
    switch (type) {
      case 'speed':
        metricUnit = 'km/h';
        break;
      case 'distance':
      case 'short_distance':
        metricUnit = 'm';
        break;
      case 'height':
        metricUnit = 'cm';
        break;
      default:
        return { displayValue: value, unit: '', alternateDisplay: '', tooltipText: undefined };
    }
    
    alternateSystem = system === 'metric' ? 'imperial' : 'metric';
    displayUnit = getDisplayUnit(metricUnit, system);
    const alternateUnit = getDisplayUnit(metricUnit, alternateSystem);
    
    const displayValue = convertValueFromMetric(value, displayUnit, metricUnit);
    const alternateValue = convertValueFromMetric(value, alternateUnit, metricUnit);
    
    const alternateDisplay = showBothUnits ? ` (${alternateValue} ${alternateUnit})` : '';
    const tooltipText = showBothUnits ? undefined : `${alternateValue} ${alternateUnit}`;
    
    return { displayValue, unit: displayUnit, alternateDisplay, tooltipText };
  }, [value, type, unitPreferences.measurement_system, showBothUnits]);

  return (
    <span className={className} title={tooltipText}>
      {displayValue} {unit}{alternateDisplay}
    </span>
  );
}