import * as React from "react";
import { Text } from "react-native";
import { omit } from "ramda";
import {
  textTransform,
  dateFormat,
} from "@applicaster/zapp-react-native-utils/cellUtils";

import { useTextLabel, withFocusedStyles } from "./hooks";
import { withScaledLineHeight } from "./utils";
import { toNumber } from "@applicaster/zapp-react-native-utils/numberUtils";
import { MeasurementPortalContext } from "../../../MeasurmentsPortal";
import { isNilOrEmpty } from "@applicaster/zapp-react-native-utils/reactUtils/helpers";

type Props = {
  style: any;
  label: string;
  transformText: string;
  entry?: any;
  dateTransformEnabled: boolean;
  dateTransform: string;
  [key: string]: any;
};

const withoutLabel = omit(["label"]);

const _Text = ({
  style,
  label,
  entry,
  transformText = "default",
  dateTransformEnabled = false,
  dateTransform,
  ...otherProps
}: Props) => {
  const _label = useTextLabel({ label, entry });
  const isMeasurement = React.useContext(MeasurementPortalContext);

  if (isNilOrEmpty(_label)) {
    return null;
  }

  // set maximum possible height for the text in case of measurement
  const height =
    isMeasurement && otherProps.numberOfLines && style.lineHeight
      ? toNumber(otherProps.numberOfLines) * toNumber(style.lineHeight)
      : undefined;

  return (
    <Text
      style={[
        withScaledLineHeight(withFocusedStyles({ style, otherProps })),
        { height },
      ]}
      {...withoutLabel(otherProps)}
    >
      {dateTransformEnabled
        ? dateFormat(dateTransform, label)
        : textTransform(transformText, _label)}
    </Text>
  );
};

export default _Text;
