import React from "react";

import FormHelperText from "@mui/material/FormHelperText";
import Grid from "@mui/material/Grid2";
import Stack from "@mui/material/Stack";
import Switch from "@mui/material/Switch";
import Typography from "@mui/material/Typography";

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

import { CardFieldBaseProps } from "./shared";

export interface CardFieldSwitchProps
  extends Omit<CardFieldBaseProps, "fallback" | "fallbackPredicate">,
    React.PropsWithChildren {
  fallback?: never;
  fallbackPredicate?: never;
  isEditable?: boolean;
  off?: string;
  offValue?: string;
  on?: string;
  onValue?: string;
  type: "switch";
  value: boolean;
}

export const CardFieldSwitch: React.FC<Omit<CardFieldSwitchProps, "type">> = ({
  formName,
  helperText,
  isDisabled = false,
  isEditable = true,
  isReadable = true,
  label,
  offValue,
  onValue,
  required = false,
  size = "grow",
  value: defaultValue,
}) => {
  const { isCompact, isEditing } = useCardContext();
  const { t } = useI18n();

  return (
    <Grid size={size}>
      {isEditing && isEditable ? (
        <Stack direction="column" height="100%" justifyContent="center">
          <Stack
            alignItems="center"
            direction={"row"}
            justifyContent={isCompact ? "space-between" : "start"}
          >
            <Typography variant="subtitle2">{label}</Typography>

            <Switch
              defaultChecked={Boolean(defaultValue)}
              disabled={isDisabled}
              name={formName}
              required={required}
              size={isCompact ? "small" : "medium"}
            />
          </Stack>

          {helperText != null && <FormHelperText sx={{ mb: 1 }}>{helperText}</FormHelperText>}
        </Stack>
      ) : (
        isReadable && (
          <LabeledValue
            compact={isCompact}
            label={label}
            value={defaultValue ? (onValue ?? t("Yes")) : (offValue ?? t("No"))}
          />
        )
      )}
    </Grid>
  );
};

export default CardFieldSwitch;
