import { X } from 'lucide-react'
import { Input } from '@/components/ui/input'
import type { Tag } from '../../services/api'
import type { PhotoTagSummary } from './PhotoInfoPanel'

interface TagsEditorProps {
  photoTags: PhotoTagSummary[]
  allTags: Tag[]
  tagInput: string
  onTagInputChange: (value: string) => void
  onAttachExisting: (id: string) => void
  onCreateAndAttach: (name: string) => void
  onRemove: (id: string) => void
}

/**
 * Single-photo tag editor. Shows the photo's current tags as chips,
 * offers an inline search that surfaces up to 6 matching unused tags,
 * and an explicit "Create" affordance when the typed name doesn't
 * exist. Used by PhotoInfoPanel in the single-selection right panel.
 */
export function TagsEditor({
  photoTags,
  allTags,
  tagInput,
  onTagInputChange,
  onAttachExisting,
  onCreateAndAttach,
  onRemove,
}: TagsEditorProps) {
  const trimmed = tagInput.trim()
  const lowerTrimmed = trimmed.toLowerCase()
  const photoTagIds = new Set(photoTags.map((t) => t.id))

  const suggestions = trimmed
    ? allTags
        .filter(
          (t) =>
            !photoTagIds.has(t.id) &&
            t.name.toLowerCase().includes(lowerTrimmed)
        )
        .slice(0, 6)
    : []

  const exactMatch = trimmed
    ? allTags.find((t) => t.name.toLowerCase() === lowerTrimmed)
    : null

  const handleSubmit = () => {
    if (!trimmed) return
    if (exactMatch) {
      if (!photoTagIds.has(exactMatch.id)) {
        onAttachExisting(exactMatch.id)
      }
      onTagInputChange('')
    } else {
      onCreateAndAttach(trimmed)
    }
  }

  return (
    <div className="space-y-2">
      {photoTags.length > 0 ? (
        <div className="flex flex-wrap gap-1">
          {photoTags.map((tag) => (
            <span
              key={tag.id}
              className="flex items-center gap-1 rounded bg-surface-2 px-2 py-0.5 text-xs text-text"
              style={
                tag.color
                  ? { backgroundColor: `${tag.color}33`, color: tag.color }
                  : undefined
              }
            >
              {tag.name}
              <button
                onClick={() => onRemove(tag.id)}
                className="rounded p-0.5 opacity-60 hover:bg-surface-offset hover:opacity-100"
                title="Remove tag"
              >
                <X className="h-3 w-3" />
              </button>
            </span>
          ))}
        </div>
      ) : (
        <div className="text-xs text-text-faint">No tags</div>
      )}

      <div className="relative">
        <Input
          type="text"
          value={tagInput}
          onChange={(e) => onTagInputChange(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter') {
              e.preventDefault()
              handleSubmit()
            } else if (e.key === 'Escape') {
              onTagInputChange('')
            }
          }}
          placeholder="Add tag…"
          className="h-7 bg-bg text-xs"
        />
        {suggestions.length > 0 && (
          <div className="mt-1 rounded border border-border bg-bg shadow-md">
            {suggestions.map((s) => (
              <button
                key={s.id}
                onClick={() => {
                  onAttachExisting(s.id)
                  onTagInputChange('')
                }}
                className="block w-full px-2 py-1 text-left text-xs text-text hover:bg-surface-2"
              >
                {s.name}
              </button>
            ))}
          </div>
        )}
        {trimmed && !exactMatch && (
          <button
            onClick={handleSubmit}
            className="mt-1 w-full rounded border border-dashed border-primary/50 px-2 py-1 text-left text-xs text-primary hover:bg-primary/10"
          >
            + Create "{trimmed}"
          </button>
        )}
      </div>
    </div>
  )
}
