"use client"

import { useState, useRef, KeyboardEvent } from "react"
import { XIcon } from "lucide-react"
import { Input } from "@/src/components/ui/input"

type Props = {
  value: string[]
  onChange: (value: string[]) => void
  disabled?: boolean
}

export function IngredientInput({ value, onChange, disabled }: Props) {
  const [draft, setDraft] = useState("")
  const inputRef = useRef<HTMLInputElement>(null)

  const add = (raw: string) => {
    const tag = raw.trim().toLowerCase()
    if (!tag || value.includes(tag)) return
    onChange([...value, tag])
    setDraft("")
  }

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

  const handleKey = (e: KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter" || e.key === ",") {
      e.preventDefault()
      add(draft)
    }
    if (e.key === "Backspace" && draft === "" && value.length > 0) {
      onChange(value.slice(0, -1))
    }
  }

  return (
    <div
      className="flex flex-wrap gap-1.5 rounded-lg border border-input bg-transparent px-3 py-2 min-h-10 cursor-text"
      onClick={() => inputRef.current?.focus()}
    >
      {value.map((tag, i) => (
        <span
          key={i}
          className="inline-flex items-center gap-1 rounded-md bg-muted px-2 py-0.5 text-xs font-medium"
        >
          {tag}
          {!disabled && (
            <button
              type="button"
              onClick={(e) => {
                e.stopPropagation()
                remove(i)
              }}
              className="text-muted-foreground hover:text-foreground"
            >
              <XIcon className="size-3" />
            </button>
          )}
        </span>
      ))}
      <Input
        ref={inputRef}
        value={draft}
        onChange={(e) => setDraft(e.target.value)}
        onKeyDown={handleKey}
        onBlur={() => add(draft)}
        disabled={disabled}
        placeholder={value.length === 0 ? "oignon, lait, farine…" : ""}
        className="h-auto flex-1 min-w-24 border-0 p-0 text-sm focus-visible:ring-0 shadow-none bg-transparent"
      />
    </div>
  )
}
