import { LabeledInput } from '@/components/ra-inputs/LabeledInput';
import { parseTime } from '@/utils';
import { styled } from '@mui/material/styles';
import { TimeInput as RaTimeInput, TimeInputProps } from 'react-admin';

function defaultFormatter(v: string): string {
  if (!v) {
    return '';
  }
  const time = parseTime(v);
  if (time) {
    return time.format('HH:mm');
  }
  return '';
}
function defaultParser(v: string): string {
  return v;
}

const StyledTimeInput = styled(RaTimeInput, { slot: 'root' })(({ label }) => ({
  '& legend': {
    width: label === false ? 0 : 'auto'
  }
}));

function TimeInput({ parse = defaultParser, format = defaultFormatter, ...props }: TimeInputProps): JSX.Element {
  return (
    // @ts-ignore
    <LabeledInput {...props}>
      {/* @ts-ignore */}
      <StyledTimeInput parse={parse} format={format} {...props} />
    </LabeledInput>
  );
}

export { TimeInput };
export type { TimeInputProps };
