import React, { forwardRef, ForwardedRef, ElementType, ComponentPropsWithoutRef } from 'react';

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;

interface ResponsiveSpacing {
  base?: Spacing;
  md?: Spacing;
  lg?: Spacing;
}

export interface BoxProps<T extends ElementType> {
  as?: T;
  children?: React.ReactNode;
  className?: string;
  center?: boolean;
  fullWidth?: boolean;
  fullHeight?: boolean;
  m?: Spacing | ResponsiveSpacing;
  mt?: Spacing | ResponsiveSpacing;
  mb?: Spacing | ResponsiveSpacing;
  ml?: Spacing | ResponsiveSpacing;
  mr?: Spacing | ResponsiveSpacing;
  mx?: Spacing | 'auto' | ResponsiveSpacing;
  my?: Spacing | ResponsiveSpacing;
  p?: Spacing | ResponsiveSpacing;
  pt?: Spacing | ResponsiveSpacing;
  pb?: Spacing | ResponsiveSpacing;
  pl?: Spacing | ResponsiveSpacing;
  pr?: Spacing | ResponsiveSpacing;
  px?: Spacing | ResponsiveSpacing;
  py?: Spacing | ResponsiveSpacing;
  display?: 'block' | 'inline-block' | 'flex' | 'inline-flex' | 'grid' | 'none';
  flexDirection?: 'row' | 'row-reverse' | 'col' | 'col-reverse';
  alignItems?: 'start' | 'center' | 'end' | 'stretch' | 'baseline';
  justifyContent?: 'start' | 'center' | 'end' | 'between' | 'around' | 'evenly';
  flexWrap?: 'wrap' | 'nowrap' | 'wrap-reverse';
  flexShrink?: number;
  flexGrow?: number;
  gridCols?: number | string;
  responsiveGridCols?: {
    base?: number | string;
    md?: number | string;
    lg?: number | string;
  };
  gap?: Spacing;
  position?: 'relative' | 'absolute' | 'fixed' | 'sticky';
  top?: Spacing | string;
  bottom?: Spacing | string;
  left?: Spacing | string;
  right?: Spacing | string;
  overflow?: 'visible' | 'hidden' | 'scroll' | 'auto';
  maxWidth?: string;
  zIndex?: number;
  w?: string | ResponsiveValue<string>;
  h?: string | ResponsiveValue<string>;
  width?: string;
  height?: string;
  rounded?: 'none' | 'sm' | 'md' | 'lg' | 'xl' | '2xl' | 'full';
  border?: boolean;
  borderColor?: string;
  bg?: string;
  shadow?: string;
  hoverBorderColor?: string;
  transition?: boolean;
}

type ResponsiveValue<T> = {
  base?: T;
  md?: T;
  lg?: T;
};

export const Box = forwardRef(<T extends ElementType = 'div'>(
  { 
    as, 
    children, 
    className = '', 
    center = false,
    fullWidth = false,
    fullHeight = false,
    m, mt, mb, ml, mr, mx, my,
    p, pt, pb, pl, pr, px, py,
    display,
    position,
    top,
    bottom,
    left,
    right,
    overflow,
    maxWidth,
    zIndex,
    gridCols,
    responsiveGridCols,
    gap,
    w,
    h,
    rounded,
    border,
    borderColor,
    bg,
    shadow,
    flexShrink,
    flexGrow,
    hoverBorderColor,
    transition,
    ...props 
  }: BoxProps<T> & ComponentPropsWithoutRef<T>,
  ref: ForwardedRef<HTMLElement>
) => {
  const Tag = (as as ElementType) || 'div';
  
  const spacingMap: Record<string | 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',
    'auto': 'auto'
  };

  const getSpacingClass = (prefix: string, value: Spacing | 'auto' | ResponsiveSpacing | undefined) => {
    if (value === undefined) return '';
    if (typeof value === 'object') {
      const classes = [];
      if (value.base !== undefined) classes.push(`${prefix}-${spacingMap[value.base]}`);
      if (value.md !== undefined) classes.push(`md:${prefix}-${spacingMap[value.md]}`);
      if (value.lg !== undefined) classes.push(`lg:${prefix}-${spacingMap[value.lg]}`);
      return classes.join(' ');
    }
    return `${prefix}-${spacingMap[value]}`;
  };

  const getResponsiveClasses = (prefix: string, value: string | ResponsiveValue<string> | undefined) => {
    if (value === undefined) return '';
    if (typeof value === 'object') {
      const classes = [];
      if (value.base !== undefined) classes.push(`${prefix}-${value.base}`);
      if (value.md !== undefined) classes.push(`md:${prefix}-${value.md}`);
      if (value.lg !== undefined) classes.push(`lg:${prefix}-${value.lg}`);
      return classes.join(' ');
    }
    return `${prefix}-${value}`;
  };

  const classes = [
    center ? 'flex items-center justify-center' : '',
    fullWidth ? 'w-full' : '',
    fullHeight ? 'h-full' : '',
    getSpacingClass('m', m),
    getSpacingClass('mt', mt),
    getSpacingClass('mb', mb),
    getSpacingClass('ml', ml),
    getSpacingClass('mr', mr),
    getSpacingClass('mx', mx),
    getSpacingClass('my', my),
    getSpacingClass('p', p),
    getSpacingClass('pt', pt),
    getSpacingClass('pb', pb),
    getSpacingClass('pl', pl),
    getSpacingClass('pr', pr),
    getSpacingClass('px', px),
    getSpacingClass('py', py),
    getResponsiveClasses('w', w),
    getResponsiveClasses('h', h),
    rounded ? `rounded-${rounded}` : '',
    border ? 'border' : '',
    borderColor ? borderColor : '',
    bg ? bg : '',
    shadow ? shadow : '',
    flexShrink !== undefined ? `flex-shrink-${flexShrink}` : '',
    flexGrow !== undefined ? `flex-grow-${flexGrow}` : '',
    hoverBorderColor ? `hover:${hoverBorderColor}` : '',
    transition ? 'transition-all' : '',
    display ? display : '',
    gridCols ? `grid-cols-${gridCols}` : '',
    responsiveGridCols?.base ? `grid-cols-${responsiveGridCols.base}` : '',
    responsiveGridCols?.md ? `md:grid-cols-${responsiveGridCols.md}` : '',
    responsiveGridCols?.lg ? `lg:grid-cols-${responsiveGridCols.lg}` : '',
    gap !== undefined ? `gap-${spacingMap[gap]}` : '',
    position ? position : '',
    top !== undefined && spacingMap[top as any] ? `top-${spacingMap[top as any]}` : '',
    bottom !== undefined && spacingMap[bottom as any] ? `bottom-${spacingMap[bottom as any]}` : '',
    left !== undefined && spacingMap[left as any] ? `left-${spacingMap[left as any]}` : '',
    right !== undefined && spacingMap[right as any] ? `right-${spacingMap[right as any]}` : '',
    overflow ? `overflow-${overflow}` : '',
    zIndex !== undefined ? `z-${zIndex}` : '',
    className
  ].filter(Boolean).join(' ');

  const style: React.CSSProperties = {
    ...(maxWidth ? { maxWidth } : {}),
    ...(top !== undefined && !spacingMap[top as any] ? { top } : {}),
    ...(bottom !== undefined && !spacingMap[bottom as any] ? { bottom } : {}),
    ...(left !== undefined && !spacingMap[left as any] ? { left } : {}),
    ...(right !== undefined && !spacingMap[right as any] ? { right } : {}),
    ...((props as Record<string, unknown>).style as object || {})
  };

  return (
    <Tag ref={ref as React.ForwardedRef<HTMLElement>} className={classes} {...props} style={style as React.CSSProperties}>
      {children}
    </Tag>
  );
});

Box.displayName = 'Box';
