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 { toNumber } from "@applicaster/zapp-react-native-utils/numberUtils";
import { MeasurementPortalContext } from "../../../MeasurmentsPortal";
import { isNilOrEmpty } from "@applicaster/zapp-react-native-utils/reactUtils/helpers";
import { CellFocusedStateContext } from "@applicaster/zapp-react-native-ui-components/Contexts/CellFocusedStateContext";
import { useAccessibilityManager } from "@applicaster/zapp-react-native-utils/appUtils/accessibilityManager/hooks";

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);
  const cellFocused = React.useContext(CellFocusedStateContext);

  const accessibilityManager = useAccessibilityManager({});

  // 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;

  const textLabel = dateTransformEnabled
    ? dateFormat(dateTransform, label)
    : textTransform(transformText, _label);

  React.useLayoutEffect(() => {
    if (cellFocused) {
      switch (otherProps.state) {
        case "focused":
          accessibilityManager.addHeading(textLabel);
          break;
        case "focused_selected":
          accessibilityManager.addHeading(`${textLabel}, Selected`);
          break;
      }
    }
  }, [cellFocused, otherProps.state, textLabel]);

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

  return (
    <Text
      style={[withFocusedStyles({ style, otherProps }), { height }]}
      {...withoutLabel(otherProps)}
      allowFontScaling={false}
    >
      {textLabel}
    </Text>
  );
};

export default _Text;
