import React, { ReactNode, ElementType, ComponentPropsWithoutRef } from 'react';
import { Box, BoxProps } from './primitives/Box';

type Spacing = 0 | 0.5 | 1 | 1.5 | 2 | 2.5 | 3 | 3.5 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 14 | 16 | 20 | 24 | 28 | 32 | 36 | 40 | 44 | 48 | 52 | 56 | 60 | 64 | 72 | 80 | 96;

type TextSize = 'xs' | 'sm' | 'base' | 'lg' | 'xl' | '2xl' | '3xl' | '4xl';

interface ResponsiveTextSize {
  base?: TextSize;
  sm?: TextSize;
  md?: TextSize;
  lg?: TextSize;
  xl?: TextSize;
  '2xl'?: TextSize;
}

type TextAlign = 'left' | 'center' | 'right';

interface ResponsiveTextAlign {
  base?: TextAlign;
  sm?: TextAlign;
  md?: TextAlign;
  lg?: TextAlign;
  xl?: TextAlign;
  '2xl'?: TextAlign;
}

interface TextProps<T extends ElementType = 'span'> extends Omit<BoxProps<T>, 'children' | 'className' | 'size'> {
  as?: T;
  children: ReactNode;
  className?: string;
  size?: TextSize | ResponsiveTextSize;
  weight?: 'light' | 'normal' | 'medium' | 'semibold' | 'bold' | string;
  color?: string;
  font?: 'mono' | 'sans' | string;
  align?: TextAlign | ResponsiveTextAlign;
  truncate?: boolean;
  uppercase?: boolean;
  capitalize?: boolean;
  letterSpacing?: 'tighter' | 'tight' | 'normal' | 'wide' | 'wider' | 'widest' | '0.05em' | string;
  leading?: 'none' | 'tight' | 'snug' | 'normal' | 'relaxed' | 'loose';
  fontSize?: string;
  style?: React.CSSProperties;
  block?: boolean;
  italic?: boolean;
  lineClamp?: number;
  ml?: Spacing | ResponsiveSpacing;
  mr?: Spacing | ResponsiveSpacing;
  mt?: Spacing | ResponsiveSpacing;
  mb?: Spacing | ResponsiveSpacing;
}

interface ResponsiveSpacing {
  base?: Spacing;
  sm?: Spacing;
  md?: Spacing;
  lg?: Spacing;
  xl?: Spacing;
  '2xl'?: Spacing;
}

export function Text<T extends ElementType = 'span'>({ 
  as,
  children, 
  className = '', 
  size = 'base',
  weight = 'normal',
  color = '',
  font = 'sans',
  align = 'left',
  truncate = false,
  uppercase = false,
  capitalize = false,
  letterSpacing,
  leading,
  fontSize,
  style,
  block = false,
  italic = false,
  lineClamp,
  ml, mr, mt, mb,
  ...props
}: TextProps<T> & ComponentPropsWithoutRef<T>) {
  const Tag = (as as ElementType) || 'span';

  const sizeClasses: Record<string, string> = {
    xs: 'text-xs',
    sm: 'text-sm',
    base: 'text-base',
    lg: 'text-lg',
    xl: 'text-xl',
    '2xl': 'text-2xl',
    '3xl': 'text-3xl',
    '4xl': 'text-4xl'
  };

  const getSizeClasses = (value: TextSize | ResponsiveTextSize | undefined) => {
    if (value === undefined) return '';
    if (typeof value === 'object') {
      const classes = [];
      if (value.base) classes.push(sizeClasses[value.base]);
      if (value.sm) classes.push(`sm:${sizeClasses[value.sm]}`);
      if (value.md) classes.push(`md:${sizeClasses[value.md]}`);
      if (value.lg) classes.push(`lg:${sizeClasses[value.lg]}`);
      if (value.xl) classes.push(`xl:${sizeClasses[value.xl]}`);
      if (value['2xl']) classes.push(`2xl:${sizeClasses[value['2xl']]}`);
      return classes.join(' ');
    }
    return sizeClasses[value];
  };
  
  const weightClasses: Record<string, string> = {
    light: 'font-light',
    normal: 'font-normal',
    medium: 'font-medium',
    semibold: 'font-semibold',
    bold: 'font-bold'
  };
  
  const fontClasses: Record<string, string> = {
    mono: 'font-mono',
    sans: 'font-sans'
  };
  
  const alignClasses: Record<string, string> = {
    left: 'text-left',
    center: 'text-center',
    right: 'text-right'
  };

  const getAlignClasses = (value: TextAlign | ResponsiveTextAlign | undefined) => {
    if (value === undefined) return '';
    if (typeof value === 'object') {
      const classes = [];
      if (value.base) classes.push(alignClasses[value.base]);
      if (value.sm) classes.push(`sm:${alignClasses[value.sm]}`);
      if (value.md) classes.push(`md:${alignClasses[value.md]}`);
      if (value.lg) classes.push(`lg:${alignClasses[value.lg]}`);
      if (value.xl) classes.push(`xl:${alignClasses[value.xl]}`);
      if (value['2xl']) classes.push(`2xl:${alignClasses[value['2xl']]}`);
      return classes.join(' ');
    }
    return alignClasses[value];
  };

  const spacingMap: Record<number, string> = {
    0: '0', 0.5: '0.5', 1: '1', 1.5: '1.5', 2: '2', 2.5: '2.5', 3: '3', 3.5: '3.5', 4: '4',
    5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '10', 11: '11', 12: '12', 14: '14',
    16: '16', 20: '20', 24: '24', 28: '28', 32: '32', 36: '36', 40: '40', 44: '44',
    48: '48', 52: '52', 56: '56', 60: '60', 64: '64', 72: '72', 80: '80', 96: '96'
  };
  
  const leadingClasses: Record<string, string> = {
    none: 'leading-none',
    tight: 'leading-tight',
    snug: 'leading-snug',
    normal: 'leading-normal',
    relaxed: 'leading-relaxed',
    loose: 'leading-loose'
  };
  
  const getSpacingClass = (prefix: string, value: Spacing | ResponsiveSpacing | undefined) => {
    if (value === undefined) return '';
    if (typeof value === 'object') {
      const classes = [];
      if (value.base !== undefined) classes.push(`${prefix}-${spacingMap[value.base as number]}`);
      if (value.sm !== undefined) classes.push(`sm:${prefix}-${spacingMap[value.sm as number]}`);
      if (value.md !== undefined) classes.push(`md:${prefix}-${spacingMap[value.md as number]}`);
      if (value.lg !== undefined) classes.push(`lg:${prefix}-${spacingMap[value.lg as number]}`);
      if (value.xl !== undefined) classes.push(`xl:${prefix}-${spacingMap[value.xl as number]}`);
      if (value['2xl'] !== undefined) classes.push(`2xl:${prefix}-${spacingMap[value['2xl'] as number]}`);
      return classes.join(' ');
    }
    return `${prefix}-${spacingMap[value as number]}`;
  };
  
  const classes = [
    block ? 'block' : 'inline',
    getSizeClasses(size),
    weightClasses[weight] || '',
    fontClasses[font] || '',
    getAlignClasses(align),
    leading ? leadingClasses[leading] : '',
    color,
    truncate ? 'truncate' : '',
    uppercase ? 'uppercase' : '',
    capitalize ? 'capitalize' : '',
    italic ? 'italic' : '',
    lineClamp ? `line-clamp-${lineClamp}` : '',
    letterSpacing === '0.05em' ? 'tracking-wider' : letterSpacing ? `tracking-${letterSpacing}` : '',
    getSpacingClass('ml', ml),
    getSpacingClass('mr', mr),
    getSpacingClass('mt', mt),
    getSpacingClass('mb', mb),
    className
  ].filter(Boolean).join(' ');
  
  const combinedStyle = {
    ...(fontSize ? { fontSize } : {}),
    ...(weight && !weightClasses[weight] ? { fontWeight: weight } : {}),
    ...(font && !fontClasses[font] ? { fontFamily: font } : {}),
    ...style
  };
  
  return <Box as={Tag} className={classes} style={combinedStyle} {...props}>{children}</Box>;
}
