import React, { ReactNode, forwardRef } from 'react';
import { Heading } from './Heading';
import { Spacing } from './Box';

export interface CardProps {
  children: ReactNode;
  variant?: 'default' | 'muted' | 'outline' | 'glass' | 'dark' | 'precision' | 'bordered' | 'elevated' | 'rarity-common' | 'rarity-rare' | 'rarity-epic' | 'rarity-legendary';
  title?: string | ReactNode;
  footer?: ReactNode;
  padding?: Spacing | number | any;
  className?: string;
  style?: React.CSSProperties;
  bg?: string;
  p?: number;
  onClick?: () => void;
  responsiveColSpan?: { lg: number };
  overflow?: string;
  rounded?: string | boolean;
  borderLeft?: boolean;
  borderColor?: string;
  center?: boolean;
  transition?: string | boolean;
  hoverBorderColor?: string;
  border?: boolean;
  position?: string;
  mb?: number;
  display?: string;
  alignItems?: string;
  gap?: number;
  py?: number;
  backgroundColor?: string;
  group?: boolean | any;
  w?: string | any;
  justifyContent?: string | any;
  fullHeight?: boolean | any;
}

/**
 * Card - Redesigned for "Modern Precision" theme.
 * Includes extensive compatibility props to prevent app-wide breakage.
 */
export const Card = forwardRef<HTMLDivElement, CardProps>(({ 
  children, 
  variant = 'default',
  title,
  footer,
  padding = 'md',
  className,
  style,
  bg,
  p,
  onClick,
  responsiveColSpan,
  overflow,
  rounded,
  borderLeft,
  borderColor,
  center,
  transition,
  hoverBorderColor,
  border,
  position,
  mb,
  display,
  alignItems,
  gap,
  py,
  backgroundColor,
  fullHeight,
}, ref) => {
  const variantClasses = {
    default: 'bg-[var(--ui-color-bg-surface)] border-[var(--ui-color-border-default)] shadow-sm',
    muted: 'bg-[var(--ui-color-bg-surface-muted)] border-[var(--ui-color-border-muted)]',
    outline: 'bg-transparent border-[var(--ui-color-border-default)]',
    glass: 'bg-white/[0.03] backdrop-blur-md border-white/[0.05]',
    dark: 'bg-[var(--ui-color-bg-base)] border-[var(--ui-color-border-default)]',
    precision: 'bg-[var(--ui-color-bg-surface)] border-[var(--ui-color-border-default)] shadow-[inset_0_1px_0_0_rgba(255,255,255,0.02)]',
    bordered: 'bg-[var(--ui-color-bg-surface)] border-[var(--ui-color-border-default)]',
    elevated: 'bg-[var(--ui-color-bg-surface)] border-[var(--ui-color-border-default)] shadow-md',
    'rarity-common': 'bg-gray-500/10 border-gray-500/50',
    'rarity-rare': 'bg-blue-500/10 border-blue-500/50',
    'rarity-epic': 'bg-purple-500/10 border-purple-500/50',
    'rarity-legendary': 'bg-orange-500/10 border-orange-500/50',
  };

  const paddingClasses = {
    none: 'p-0',
    sm: 'p-2',
    md: 'p-4',
    lg: 'p-8',
  };

  const getPaddingClass = (pad: any) => {
    if (typeof pad === 'string') return `p-${pad}`;
    return ''; // Handled in style
  };

  const combinedStyle: React.CSSProperties = {
    ...style,
    ...(bg ? { backgroundColor: bg.startsWith('bg-') ? undefined : bg } : {}),
    ...(backgroundColor ? { backgroundColor } : {}),
    ...(p !== undefined ? { padding: typeof p === 'number' ? `${p * 0.25}rem` : undefined } : {}),
    ...(py !== undefined ? { paddingTop: typeof py === 'number' ? `${py * 0.25}rem` : undefined, paddingBottom: typeof py === 'number' ? `${py * 0.25}rem` : undefined } : {}),
    ...(typeof padding === 'number' ? { padding: `${padding * 0.25}rem` } : {}),
    ...(responsiveColSpan?.lg ? { gridColumn: `span ${responsiveColSpan.lg} / span ${responsiveColSpan.lg}` } : {}),
    ...(overflow ? { overflow } : {}),
    ...(borderColor ? { borderColor: borderColor.startsWith('border-') ? undefined : borderColor } : {}),
    ...(borderLeft ? { borderLeft: `4px solid ${borderColor || 'var(--ui-color-intent-primary)'}` } : {}),
    ...(center ? { display: 'flex', alignItems: 'center', justifyContent: 'center' } : {}),
    ...(typeof transition === 'string' ? { transition } : {}),
    ...(position ? { position: position as any } : {}),
    ...(mb !== undefined ? { marginBottom: `${mb * 0.25}rem` } : {}),
    ...(display ? { display } : {}),
    ...(alignItems ? { alignItems } : {}),
    ...(gap !== undefined ? { gap: `${gap * 0.25}rem` } : {}),
    ...(border === false ? { border: 'none' } : {}),
    ...(fullHeight ? { height: '100%' } : {}),
  };

  return (
    <div 
      ref={ref}
      className={`border ${variantClasses[variant as keyof typeof variantClasses] || variantClasses.default} ${getPaddingClass(padding)} ${onClick ? 'cursor-pointer hover:border-[var(--ui-color-border-bright)]' : ''} ${transition === true ? 'transition-all duration-200' : ''} ${rounded === true ? 'rounded-full' : (typeof rounded === 'string' ? `rounded-${rounded}` : 'rounded-none')} ${className || ''}`}
      style={combinedStyle}
      onClick={onClick}
    >
      {title && (
        <div className={`border-b border-[var(--ui-color-border-muted)] ${getPaddingClass(padding)}`}>
          {typeof title === 'string' ? (
            <Heading level={5} weight="bold" uppercase>{title}</Heading>
          ) : title}
        </div>
      )}
      
      <div className={`${typeof padding === 'number' || p !== undefined ? '' : getPaddingClass(padding)} ${fullHeight ? 'h-full flex flex-col' : ''}`}>
        {children}
      </div>
      
      {footer && (
        <div className={`border-t border-[var(--ui-color-border-muted)] bg-white/[0.02] ${getPaddingClass(padding)}`}>
          {footer}
        </div>
      )}
    </div>
  );
});

Card.displayName = 'Card';

export const CardHeader = ({ title, children }: { title?: string, children?: ReactNode }) => (
  <div className="mb-4">
    {title && <Heading level={5} weight="bold" uppercase>{title}</Heading>}
    {children}
  </div>
);

export const CardContent = ({ children }: { children: ReactNode }) => (
  <div>{children}</div>
);

export const CardFooter = ({ children }: { children: ReactNode }) => (
  <div className="mt-4 pt-4 border-t border-[var(--ui-color-border-muted)]">
    {children}
  </div>
);
