'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;
  value?: MeasurementSystem;
  onChange?: (value: MeasurementSystem) => void;
}

/**
 * Measurement unit selector component for choosing between Metric and Imperial systems
 */
export function MeasurementUnitSelector({
  variant = 'outlined',
  fullWidth = true,
  showDescription = true,
  value,
  onChange,
}: MeasurementUnitSelectorProps) {
  const { measurementSystem, setMeasurementSystem } = useLocale();
  const { t } = useTranslation('settings');

  // Use controlled value if provided, otherwise use hook value
  const selectedSystem = value !== undefined ? value : measurementSystem;

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

    // If onChange is provided (controlled), use it
    if (onChange) {
      onChange(newSystem);
    } else {
      // Otherwise use the hook (uncontrolled)
      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>
  );
}
