"use client";

import { useRef, useState, type KeyboardEvent, type ClipboardEvent } from "react";
import { X } from "lucide-react";

export interface ChipsInputProps {
  value: string[];
  onChange: (v: string[]) => void;
  placeholder?: string;
  label?: string;
  maxItems?: number;
  maxLength?: number;
  disabled?: boolean;
  className?: string;
}

export function ChipsInput({
  value,
  onChange,
  placeholder,
  label,
  maxItems = 20,
  maxLength = 200,
  disabled = false,
  className = "",
}: ChipsInputProps) {
  const [input, setInput] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);

  function addChip(raw: string) {
    const trimmed = raw.trim().slice(0, maxLength);
    if (!trimmed) return;
    if (value.length >= maxItems) return;
    const lower = trimmed.toLowerCase();
    if (value.some((v) => v.toLowerCase() === lower)) return;
    onChange([...value, trimmed]);
  }

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

  function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {
    if (e.key === "Enter") {
      e.preventDefault();
      addChip(input);
      setInput("");
    } else if (e.key === "Backspace" && input === "" && value.length > 0) {
      removeChip(value.length - 1);
    }
  }

  function handleBlur() {
    if (input.trim()) {
      addChip(input);
      setInput("");
    }
  }

  // Paste: split on newlines only so "New Port Richey, FL" stays intact.
  // Each non-empty line becomes its own chip.
  function handlePaste(e: ClipboardEvent<HTMLInputElement>) {
    const text = e.clipboardData.getData("text");
    if (!text.includes("\n")) return; // single line: let browser handle normally
    e.preventDefault();
    const lines = text.split("\n").map((l) => l.trim()).filter(Boolean);
    let updated = [...value];
    for (const line of lines) {
      const trimmed = line.slice(0, maxLength);
      if (!trimmed) continue;
      if (updated.length >= maxItems) break;
      if (updated.some((v) => v.toLowerCase() === trimmed.toLowerCase())) continue;
      updated = [...updated, trimmed];
    }
    onChange(updated);
    setInput("");
  }

  const atMax = value.length >= maxItems;

  return (
    <div
      className={`flex flex-wrap gap-1.5 w-full min-h-[42px] rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-900 transition focus-within:ring-2 focus-within:ring-brand-500 focus-within:border-transparent cursor-text ${disabled ? "bg-slate-50 opacity-60" : "bg-white"} ${className}`}
      onClick={() => !disabled && inputRef.current?.focus()}
    >
      {value.map((chip, i) => (
        <span
          key={i}
          className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md bg-brand-50 border border-brand-200 text-brand-800 text-xs font-medium shrink-0"
        >
          {chip}
          {!disabled && (
            <button
              type="button"
              onClick={(e) => { e.stopPropagation(); removeChip(i); }}
              className="text-brand-400 hover:text-brand-700 transition-colors ml-0.5"
              aria-label={`Remove ${chip}`}
            >
              <X className="w-3 h-3" />
            </button>
          )}
        </span>
      ))}
      {!atMax && !disabled && (
        <input
          ref={inputRef}
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={handleKeyDown}
          onBlur={handleBlur}
          onPaste={handlePaste}
          placeholder={value.length === 0 ? placeholder : ""}
          className="flex-1 min-w-[120px] bg-transparent outline-none text-sm placeholder:text-slate-400"
          disabled={disabled}
        />
      )}
      {atMax && (
        <span className="text-xs text-slate-400 self-center ml-1">
          Max {maxItems}
        </span>
      )}
    </div>
  );
}
