import React, { forwardRef } from "react";

import { styled } from "../../theme";
import type { WithTestId } from "../../types";

import type { CSS, CSSSingleVariant } from "../../theme";

export const h1Variant: CSS = {
  fontSize: "$7",
  fontWeight: "$black",
  fontFamily: "$decorative",
  lineHeight: "$7",
};
export const h2Variant: CSS = {
  fontSize: "$6",
  fontWeight: "$black",
  fontFamily: "$decorative",
  lineHeight: "$6",
};
export const h3Variant: CSS = {
  fontSize: "$5",
  fontWeight: "$black",
  fontFamily: "$decorative",
  lineHeight: "$5",
};
export const h4Variant: CSS = {
  fontSize: "$4",
  fontWeight: "$black",
  fontFamily: "$decorative",
  lineHeight: "$4",
};
export const h5Variant: CSS = {
  fontSize: "$3",
  fontWeight: "$black",
  fontFamily: "$decorative",
  lineHeight: "$3",
};
export const h6Variant: CSS = {
  fontSize: "$2",
  fontWeight: "$black",
  fontFamily: "$decorative",
  lineHeight: "$2",
};

export const body1Variant: CSS = {
  fontSize: "$5",
  fontWeight: "$regular",
  fontFamily: "$text",
  lineHeight: "$5",
};

export const body2Variant: CSS = {
  fontSize: "$4",
  fontWeight: "$regular",
  fontFamily: "$text",
  lineHeight: "$4",
};

export const body3Variant: CSS = {
  fontSize: "$3",
  fontWeight: "$regular",
  fontFamily: "$text",
  lineHeight: "$3",
};

export const body4Variant: CSS = {
  fontSize: "$2",
  fontWeight: "$regular",
  fontFamily: "$text",
  lineHeight: "$2",
};

export const body5Variant: CSS = {
  fontSize: "$1",
  fontWeight: "$regular",
  fontFamily: "$text",
  lineHeight: "$1",
};

export const typographyVariants = {
  h1: h1Variant,
  h2: h2Variant,
  h3: h3Variant,
  h4: h4Variant,
  h5: h5Variant,
  h6: h6Variant,
  body1: body1Variant,
  body2: body2Variant,
  body3: body3Variant,
  body4: body4Variant,
  body5: body5Variant,
} satisfies CSSSingleVariant;

const StyledText = styled("span", {
  variants: {
    variant: typographyVariants,
    ellipsis: {
      true: {
        whiteSpace: "nowrap",
        overflow: "hidden",
        textOverflow: "ellipsis",
      },
    },
  },

  defaultVariants: {
    variant: "body1",
  },
});

export interface TextProps extends WithTestId<React.ComponentProps<typeof StyledText>> {
  as?: "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "span" | "p";
}

const parseHTMLTag = (
  variant: TextProps["variant"]
): "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "span" => {
  if (
    variant === "h1" ||
    variant === "h2" ||
    variant === "h3" ||
    variant === "h4" ||
    variant === "h5" ||
    variant === "h6"
  )
    return variant;
  return "span";
};

export const Text = forwardRef<HTMLSpanElement, TextProps>((props, ref) => {
  const { as, ...rest } = props;

  return <StyledText ref={ref} {...rest} as={as || parseHTMLTag(rest.variant)} />;
});

Text.displayName = "Text";
