import React, { forwardRef, ReactNode } from 'react';
import { Box } from './primitives/Box';
import { Stack } from './primitives/Stack';
import { Text } from './Text';

interface SelectOption {
  value: string;
  label: string;
}

interface SelectProps extends React.SelectHTMLAttributes<HTMLSelectElement> {
  label?: string;
  fullWidth?: boolean;
  pl?: number;
  errorMessage?: string;
  variant?: 'default' | 'error';
  options?: SelectOption[];
}

export const Select = forwardRef<HTMLSelectElement, SelectProps>(
  ({ label, fullWidth = true, pl, errorMessage, variant = 'default', options, children, className = '', style, ...props }, ref) => {
    const isError = variant === 'error' || !!errorMessage;
    
    const variantClasses = isError 
      ? 'border-warning-amber focus:border-warning-amber' 
      : 'border-charcoal-outline focus:border-primary-blue';
    
    const defaultClasses = `${fullWidth ? 'w-full' : 'w-auto'} px-3 py-2 bg-deep-graphite border rounded-lg text-white focus:outline-none transition-colors`;
    const classes = [
      defaultClasses,
      variantClasses,
      pl ? `pl-${pl}` : '',
      className
    ].filter(Boolean).join(' ');

    return (
      <Stack gap={1.5} fullWidth={fullWidth}>
        {label && (
          <Text as="label" size="xs" weight="bold" color="text-gray-500" uppercase letterSpacing="wider">
            {label}
          </Text>
        )}
        <Box 
          as="select" 
          ref={ref} 
          className={classes} 
          style={style} 
          {...props}
        >
          {options ? options.map(opt => (
            <option key={opt.value} value={opt.value}>{opt.label}</option>
          )) : children}
        </Box>
        {errorMessage && (
          <Text size="xs" color="text-warning-amber" mt={1}>
            {errorMessage}
          </Text>
        )}
      </Stack>
    );
  }
);

Select.displayName = 'Select';
