import React from "react";

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

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

import { CardFieldBaseProps } from "./shared";

export interface CardFieldTextProps
  extends Omit<TextFieldProps, "variant" | "size" | "helperText" | "label">,
    CardFieldBaseProps,
    React.PropsWithChildren {
  type: "text";
  multiline?: boolean;
  value?: string;
  maxLength?: number;
  minRows?: number;
  adornment?: string;
  isEditable?: boolean;
}

export const CardFieldText: React.FC<Omit<CardFieldTextProps, "type">> = ({
  label,
  fallback = "—",
  fallbackPredicate = (value: unknown) =>
    typeof value !== "string" || value == null || value === "",
  formName,
  value: defaultValue,
  required = false,
  isDisabled = false,
  size = "grow",
  isReadable = true,
  isEditable = true,
  helperText,
  ...props
}) => {
  const { isCompact, isEditing } = useCardContext();

  return (
    <Grid size={size}>
      {isEditing && isEditable ? (
        <Stack direction="column">
          <TextField
            fullWidth
            defaultValue={defaultValue ?? ""}
            disabled={isDisabled}
            label={label}
            name={formName}
            required={required}
            variant="outlined"
            {...props}
          />

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

export default CardFieldText;
