"use client";

import { useState } from "react";
import { Plus, X } from "lucide-react";
import styles from "./TagInput.module.css";

interface TagInputProps {
  label?: string;
  hint?: string;
  error?: string;
  value: string[];
  onChange: (value: string[]) => void;
  placeholder?: string;
}

export default function TagInput({ label, hint, error, value, onChange, placeholder }: TagInputProps) {
  const [draft, setDraft] = useState("");

  const addTag = () => {
    const trimmed = draft.trim();
    if (!trimmed) return;
    onChange([...value, trimmed]);
    setDraft("");
  };

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

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter") {
      e.preventDefault();
      addTag();
    } else if (e.key === "Backspace" && draft === "" && value.length > 0) {
      removeTag(value.length - 1);
    }
  };

  return (
    <div className={styles.field}>
      {label && <label className={styles.label}>{label}</label>}

      {value.length > 0 && (
        <div className={styles.tags}>
          {value.map((tag, index) => (
            <span key={`${tag}-${index}`} className={styles.tag}>
              {tag}
              <button
                type="button"
                className={styles.tagRemove}
                onClick={() => removeTag(index)}
                aria-label={`Supprimer "${tag}"`}
              >
                <X size={12} />
              </button>
            </span>
          ))}
        </div>
      )}

      <div className={styles.inputRow}>
        <input
          type="text"
          className={styles.input}
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder={placeholder}
        />
        <button type="button" className={styles.addBtn} onClick={addTag} aria-label="Ajouter">
          <Plus size={16} />
        </button>
      </div>

      {error && <span className={styles.error}>{error}</span>}
      {hint && !error && <span className={styles.hint}>{hint}</span>}
    </div>
  );
}
