import React from "react";

import Checkbox from "@mui/material/Checkbox";
import FormControlLabel from "@mui/material/FormControlLabel";
import FormHelperText from "@mui/material/FormHelperText";
import Grid from "@mui/material/Grid2";
import Stack from "@mui/material/Stack";

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

import { CardFieldBaseProps } from "./shared";

export interface CardFieldCheckboxProps
  extends React.PropsWithChildren<Omit<CardFieldBaseProps, "fallback" | "fallbackPredicate">> {
  isEditable?: boolean;
  noValue?: React.ReactNode;
  type: "checkbox";
  value: boolean;
  yesValue?: React.ReactNode;
  fallback?: never;
  fallbackPredicate?: never;
}

export const CardFieldCheckbox: React.FC<Omit<CardFieldCheckboxProps, "type">> = ({
  formName,
  helperText,
  isDisabled = false,
  isEditable = true,
  isReadable = true,
  label,
  required = false,
  size = "grow",
  value: defaultValue,
  yesValue,
  noValue,
}) => {
  const { t } = useI18n();
  const { isEditing } = useCardContext();

  return (
    <Grid size={size}>
      {isEditing && isEditable ? (
        <Stack direction="column" height="100%" justifyContent="center">
          <Stack>
            <FormControlLabel
              control={<Checkbox defaultChecked={Boolean(defaultValue)} sx={{ py: 0 }} />}
              disabled={isDisabled}
              label={label}
              name={formName}
              required={required}
            />
          </Stack>

          {helperText != null && <FormHelperText>{helperText}</FormHelperText>}
        </Stack>
      ) : (
        isReadable && (
          <LabeledValue
            label={label}
            value={defaultValue ? (yesValue ?? t("Yes")) : (noValue ?? t("No"))}
          />
        )
      )}
    </Grid>
  );
};

export default CardFieldCheckbox;
