"use client"

import * as React from "react"
import { Plus, X } from "lucide-react"
import { Badge } from "@/components/ui/badge"
import { cn } from "@/lib/utils"
import { MultiSelect } from "@/components/ui/multi-select"

export interface TagsInputProps {
  value: string[]
  onChange: (tags: string[]) => void
  placeholder?: string
  className?: string
  disabled?: boolean
}

export function TagsInput({
  value,
  onChange,
  placeholder = "Add tags...",
  className,
  disabled = false,
}: TagsInputProps) {
  const tags = value ?? []
  
  // Transform strings to MultiSelect options
  const options = tags.map(tag => ({
    label: tag,
    value: tag
  }))

  const [searchValue, setSearchValue] = React.useState("")

  const handleValueChange = (newValues: string[]) => {
    onChange(newValues)
  }

  // To allow adding new tags, we can listen to the search input and provide a "Create" option
  // However, the MultiSelect component I just wrote doesn't expose the search input's internal "Create" logic easily
  // So I'll modify MultiSelect slightly to support a 'creatable' mode or just use it as is if I can.
  
  // Actually, I'll update MultiSelect in a moment to handle this.
  // For now, let's keep TagsInput simple but using the MultiSelect base.

  return (
    <MultiSelect
      options={options}
      value={tags}
      onValueChange={handleValueChange}
      placeholder={placeholder}
      className={className}
      disabled={disabled}
      maxCount={5}
      searchable={true}
      singleLine={true}
      searchValue={searchValue}
      onSearchValueChange={setSearchValue}
      // We'll pass a custom empty indicator that allows creating the tag
      emptyIndicator={
        searchValue.trim() ? (
          <div 
            className="flex items-center gap-2 py-2 px-2 cursor-pointer hover:bg-gray-100 rounded-lg text-[13px] text-primary font-medium"
            onPointerDown={(e) => {
              e.preventDefault() // Prevent focus loss
              const newTag = searchValue.trim()
              if (newTag && !tags.includes(newTag)) {
                onChange([...tags, newTag])
              }
              setSearchValue("")
            }}
          >
            <Plus size={14} />
            Create "{searchValue}"
          </div>
        ) : (
          <div className="py-6 text-center text-[12px] text-gray-500">
            Type to search or create tags
          </div>
        )
      }
    />
  )
}
