import TextField, { type TextFieldProps } from '@mui/material/TextField';
import { useTheme } from '@mui/material/styles';

export type GermanDateMode = 'date' | 'datetime';

export interface GermanDateFieldProps extends Omit<TextFieldProps, 'value' | 'onChange' | 'type'> {
  /** ISO date (YYYY-MM-DD) or datetime (YYYY-MM-DDTHH:MM) string */
  value?: string | null;
  /** Called with ISO date/datetime string on change */
  onChange?: (isoValue: string) => void;
  mode?: GermanDateMode;
}

/**
 * Themed date / datetime input that:
 *  - Uses the native browser date picker (locale-aware → shows DD.MM.YYYY in German browsers)
 *  - Properly supports dark / light mode via CSS colorScheme
 *  - Thin wrapper: all MUI TextField props work as expected
 */
export default function GermanDateField({
  value,
  onChange,
  mode = 'date',
  sx,
  ...rest
}: GermanDateFieldProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === 'dark';

  const nativeType = mode === 'date' ? 'date' : 'datetime-local';
  const nativeValue =
    mode === 'date' ? (value?.substring(0, 10) || '') : (value?.substring(0, 16) || '');

  return (
    <TextField
      {...rest}
      type={nativeType}
      value={nativeValue}
      onChange={(e) => onChange?.(e.target.value)}
      InputLabelProps={{ shrink: true, ...rest.InputLabelProps }}
      sx={{
        '& input': {
          colorScheme: isDark ? 'dark' : 'light',
        },
        ...sx,
      }}
    />
  );
}
