/**
 * TagInput widget component for multi-value string arrays.
 *
 * ⚠️ AUTO-GENERATED BY PRISM - DO NOT EDIT
 */

import { useState, type KeyboardEvent } from 'react';
import type { WidgetBaseProps } from '../types';

interface TagInputProps extends WidgetBaseProps<string[]> {
  maxTags?: number;
  allowDuplicates?: boolean;
}

export function TagInput({
  name,
  value = [],
  onChange,
  label,
  description,
  placeholder = 'Type and press Enter...',
  required,
  disabled,
  error,
  className,
  maxTags,
  allowDuplicates = false,
}: TagInputProps): JSX.Element {
  const [inputValue, setInputValue] = useState('');
  const tags = Array.isArray(value) ? value : [];

  const addTag = (tag: string) => {
    const trimmed = tag.trim();
    if (!trimmed) return;
    if (!allowDuplicates && tags.includes(trimmed)) return;
    if (maxTags && tags.length >= maxTags) return;

    onChange([...tags, trimmed]);
    setInputValue('');
  };

  const removeTag = (index: number) => {
    const newTags = tags.filter((_, i) => i !== index);
    onChange(newTags);
  };

  const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      addTag(inputValue);
    } else if (e.key === 'Backspace' && !inputValue && tags.length > 0) {
      removeTag(tags.length - 1);
    }
  };

  return (
    <div className={className}>
      {label && (
        <label htmlFor={name} className="label">
          {label}
          {required && <span className="text-red-500 ml-1">*</span>}
        </label>
      )}
      <div
        className={`flex flex-wrap gap-2 p-2 rounded-lg border ${
          error
            ? 'border-red-500 focus-within:ring-red-500'
            : 'border-nordic-300 focus-within:ring-nordic-500'
        } focus-within:ring-2 focus-within:ring-offset-0 bg-white`}
      >
        {tags.map((tag, index) => (
          <span
            key={`${tag}-${index}`}
            className="inline-flex items-center gap-1 px-2 py-1 rounded bg-nordic-100 text-nordic-700 text-sm"
          >
            {tag}
            {!disabled && (
              <button
                type="button"
                onClick={() => removeTag(index)}
                className="text-nordic-500 hover:text-nordic-700"
                aria-label={`Remove ${tag}`}
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            )}
          </span>
        ))}
        <input
          id={name}
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onKeyDown={handleKeyDown}
          onBlur={() => addTag(inputValue)}
          placeholder={tags.length === 0 ? placeholder : ''}
          disabled={disabled || (maxTags !== undefined && tags.length >= maxTags)}
          className="flex-1 min-w-[120px] border-0 p-1 focus:ring-0 focus:outline-none text-sm"
          aria-invalid={!!error}
          aria-describedby={description ? `${name}-desc` : error ? `${name}-error` : undefined}
        />
      </div>
      {maxTags && (
        <p className="mt-1 text-xs text-nordic-400">
          {tags.length}/{maxTags} tags
        </p>
      )}
      {description && !error && (
        <p id={`${name}-desc`} className="mt-1.5 text-sm text-nordic-500">{description}</p>
      )}
      {error && (
        <p id={`${name}-error`} className="mt-1.5 text-sm text-red-600">
          {error}
        </p>
      )}
    </div>
  );
}
