'use client';

import { useState, useEffect } from 'react';
import {
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  SelectChangeEvent,
  Box,
  Typography,
} from '@mui/material';
import { useLocale, MeasurementSystem } from '@/hooks/useLocale';
import { useTranslation } from '@/hooks/useTranslation';

interface MeasurementUnitSelectorProps {
  variant?: 'standard' | 'outlined' | 'filled';
  fullWidth?: boolean;
  showDescription?: boolean;
}

/**
 * Measurement unit selector component for choosing between Metric and Imperial systems
 */
export function MeasurementUnitSelector({
  variant = 'outlined',
  fullWidth = true,
  showDescription = true,
}: MeasurementUnitSelectorProps) {
  const { measurementSystem, setMeasurementSystem } = useLocale();
  const { t } = useTranslation('settings');
  const [selectedSystem, setSelectedSystem] = useState<MeasurementSystem>(measurementSystem);

  useEffect(() => {
    setSelectedSystem(measurementSystem);
  }, [measurementSystem]);

  const handleSystemChange = (event: SelectChangeEvent) => {
    const newSystem = event.target.value as MeasurementSystem;
    setSelectedSystem(newSystem);
    setMeasurementSystem(newSystem);
  };

  return (
    <FormControl variant={variant} fullWidth={fullWidth}>
      <InputLabel id="measurement-unit-selector-label">
        {t('preferences.measurementUnits')}
      </InputLabel>
      <Select
        labelId="measurement-unit-selector-label"
        id="measurement-unit-selector"
        value={selectedSystem}
        label={t('preferences.measurementUnits')}
        onChange={handleSystemChange}
      >
        <MenuItem value="metric">
          <Box>
            <Typography variant="body1">{t('preferences.metric')}</Typography>
            {showDescription && (
              <Typography variant="caption" color="text.secondary">
                kg, cm, °C, ml
              </Typography>
            )}
          </Box>
        </MenuItem>
        <MenuItem value="imperial">
          <Box>
            <Typography variant="body1">{t('preferences.imperial')}</Typography>
            {showDescription && (
              <Typography variant="caption" color="text.secondary">
                lb, in, °F, oz
              </Typography>
            )}
          </Box>
        </MenuItem>
      </Select>
    </FormControl>
  );
}
