---
import type { HTMLAttributes } from 'astro/types';
import { cn } from '@/lib/cn';
import { generateId } from '@/lib/utils';
import { inputVariants, inputSizeConfig } from './input.variants';

interface Props extends HTMLAttributes<'input'> {
  label?: string;
  error?: string;
  hint?: string;
  size?: 'sm' | 'md' | 'lg';
  /** Icon name to display at the start of the input */
  leadingIcon?: string;
  /** Icon name to display at the end of the input */
  trailingIcon?: string;
}

const { label, error, hint, size = 'md', leadingIcon, trailingIcon, class: className, id, ...attrs } = Astro.props;

const inputId = id || generateId('input');
const config = inputSizeConfig[size];

const inputStyles = cn(
  inputVariants({ size }),
  error && 'border-destructive focus-visible:ring-destructive',
  leadingIcon ? config.leadingPadding : config.baseLeftPadding,
  trailingIcon ? config.trailingPadding : config.baseRightPadding
);

const iconStyles = cn(
  'absolute top-0 flex items-center justify-center h-full pointer-events-none',
  'text-foreground-muted',
  config.iconWrapper
);

// Dynamic icon import
import Icon from '../../primitives/Icon/Icon.astro';
---

<div class={cn('space-y-1.5', className)}>
  {
    label && (
      <label for={inputId} class="text-sm font-medium leading-none">
        {label}
      </label>
    )
  }

  <div class="relative">
    {
      leadingIcon && (
        <div class={cn(iconStyles, 'left-0')}>
          <Icon name={leadingIcon} size="sm" />
        </div>
      )
    }

    <input
      id={inputId}
      class={inputStyles}
      aria-invalid={error ? 'true' : undefined}
      aria-describedby={error ? `${inputId}-error` : hint ? `${inputId}-hint` : undefined}
      {...attrs}
    />

    {
      trailingIcon && (
        <div class={cn(iconStyles, 'right-0')}>
          <Icon name={trailingIcon} size="sm" />
        </div>
      )
    }
  </div>

  {
    error && (
      <p id={`${inputId}-error`} class="text-sm text-destructive">
        {error}
      </p>
    )
  }

  {
    hint && !error && (
      <p id={`${inputId}-hint`} class="text-sm text-muted-foreground">
        {hint}
      </p>
    )
  }
</div>
