import React from "react";

import { FormHelperText, Stack } from "@mui/material";
import Grid from "@mui/material/Grid2";
import InputAdornment from "@mui/material/InputAdornment";
import TextField from "@mui/material/TextField";

import { useCardContext } from "../../contexts/CardContext";
import LabeledValue from "../LabeledValue";

import { CardFieldBaseProps } from "./shared";

export interface CardFieldNumberProps extends CardFieldBaseProps, React.PropsWithChildren {
  type: "number";
  value?: number;
  min?: number;
  max?: number;
  adornment?: string;
  disabled?: boolean;
  isEditable?: boolean;
}

export const CardFieldNumber: React.FC<Omit<CardFieldNumberProps, "type">> = ({
  adornment,
  disabled,
  fallback = "—",
  fallbackPredicate = (value) => value == null,
  formName,
  helperText,
  isDisabled = false,
  isEditable = true,
  isReadable = true,
  label,
  required = false,
  size = "grow",
  value: defaultValue,
  ...props
}) => {
  const { isCompact, isEditing } = useCardContext();

  return (
    <Grid size={size}>
      {isEditing && isEditable ? (
        <Stack direction="column">
          <TextField
            fullWidth
            defaultValue={defaultValue ?? ""}
            disabled={isDisabled || disabled}
            inputProps={{
              min: "min" in props ? props.min : undefined,
              max: "max" in props ? props.max : undefined,
            }}
            label={label}
            name={formName}
            required={required}
            slotProps={{
              input: {
                endAdornment: <InputAdornment position="end">{adornment}</InputAdornment>,
              },
            }}
            type="number"
            variant="outlined"
          />

          {helperText != null && <FormHelperText sx={{ mb: 1 }}>{helperText}</FormHelperText>}
        </Stack>
      ) : (
        isReadable && (
          <LabeledValue
            compact={isCompact}
            label={label}
            value={fallbackPredicate(defaultValue) ? fallback : defaultValue}
          />
        )
      )}
    </Grid>
  );
};

export default CardFieldNumber;
