import { styleMap } from "./textStyleMap";
import clsx from "clsx";
import React, { JSX } from "react";

const variantColors = {
  default: "text-black",
  danger: "text-red-600",
  success: "text-green-600",
  warning: "text-yellow-500",
  info: "text-blue-500",
} as const;

type Variant = keyof typeof variantColors;
type StyleValue = { mobile: string; tablet: string; web: string };
type ElementTag = keyof JSX.IntrinsicElements;

type TextComponentProps = {
  token: string;
  variant?: Variant;
  className?: string;
  as?: ElementTag;
  children: React.ReactNode;
};

type StyleMap = typeof styleMap;

function createTextComponent<T extends keyof StyleMap>(
  type: T,
  styleMap: StyleMap
) {
  return ({
    token,
    variant = "default",
    className = "",
    as: Tag = "span",
    children,
  }: TextComponentProps) => {
    const styleGroup = styleMap[type] as Record<string, StyleValue>;
    const styles = styleGroup[token];

    if (!styles) {
      console.warn(`[TextStyle.${type}] Unknown token: ${token}`);
      return <Tag className={clsx(className)}>{children}</Tag>;
    }

    return (
      <Tag
        className={clsx(
          styles.mobile,
          styles.tablet,
          styles.web,
          variantColors[variant],
          className
        )}
      >
        {children}
      </Tag>
    );
  };
}

function createTextStyle(customStyleMap?: StyleMap) {
  const defaultStyleMap = customStyleMap ?? styleMap;

  return {
    Display: createTextComponent("display", defaultStyleMap),
    Heading: createTextComponent("heading", defaultStyleMap),
    Body: createTextComponent("body", defaultStyleMap),
    Button: createTextComponent("button", defaultStyleMap),
    Caption: createTextComponent("caption", defaultStyleMap),
  };
}

const TextStyle = createTextStyle();

export { createTextStyle, TextStyle };
export default TextStyle;
