import * as R from "ramda";
import { toNumberWithDefaultZero } from "@applicaster/zapp-react-native-utils/numberUtils";

import { Button } from "./Button";
import {
  getButtonsCount,
  getPluginIdentifier,
  mapSelfAlignment,
} from "./utils";

import { compact } from "@applicaster/zapp-react-native-utils/cellUtils";

export {
  insertButtonsBetweenLabels,
  insertButtonsBetweenLabelContainers,
} from "./utils";

const PREFIX = "tv_buttons";

type Props = {
  value: Function;
  platformValue: Function;
  configuration: Record<string, unknown>;
  state: string;
  skipButtons: boolean;
};

export const TvActionButtons = ({
  value,
  platformValue,
  configuration,
  state,
  skipButtons,
}: Props) => {
  if (skipButtons || !value(`${PREFIX}_container_buttons_enabled`)) {
    return null;
  }

  const buttonsCount = getButtonsCount(configuration, PREFIX);

  if (buttonsCount <= 0) {
    return null;
  }

  const prefix1Button = `${PREFIX}_button_1`;
  const independentStyles = value(`${PREFIX}_container_independent_styles`);

  return {
    type: "ButtonContainerView",
    style: {
      flexDirection: "row",

      justifyContent: mapSelfAlignment(value(`${PREFIX}_container_align`)),

      marginTop: toNumberWithDefaultZero(
        value(`${PREFIX}_container_margin_top`)
      ),
      marginRight: toNumberWithDefaultZero(
        value(`${PREFIX}_container_margin_right`)
      ),
      marginBottom: toNumberWithDefaultZero(
        value(`${PREFIX}_container_margin_bottom`)
      ),
      marginLeft: toNumberWithDefaultZero(
        value(`${PREFIX}_container_margin_left`)
      ),
    },
    additionalProps: {
      horizontalGutter: toNumberWithDefaultZero(
        value(`${PREFIX}_container_horizontal_gutter`)
      ),
      state,
      buttonsCount,
    },
    elements: compact(
      R.times((index) => {
        const prefixSpecificButton = `${PREFIX}_button_${index + 1}`;

        return Button({
          prefix: independentStyles ? prefixSpecificButton : prefix1Button,
          value,
          platformValue,
          pluginIdentifier: getPluginIdentifier(configuration, PREFIX, index),
          suffixId: prefixSpecificButton,
          preferredFocus: index === 0,
        });
      }, buttonsCount)
    ),
  };
};
