"use client";

import { useState } from "react";

export function AreaTagInput({ areaOptions, initialAreas }: { areaOptions: string[]; initialAreas: string[] }) {
  const [tags, setTags] = useState<string[]>(initialAreas);
  const [input, setInput] = useState("");

  function addTag(value: string) {
    const v = value.trim();
    if (v && areaOptions.includes(v) && !tags.includes(v)) {
      setTags((t) => [...t, v]);
    }
    setInput("");
  }

  function removeTag(v: string) {
    setTags((t) => t.filter((x) => x !== v));
  }

  return (
    <div className="flex flex-1 flex-wrap items-center gap-1.5 rounded-full border border-stone-300 bg-white px-3 py-2">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="flex-none text-stone-400">
        <circle cx="11" cy="11" r="8" />
        <path d="m21 21-4.3-4.3" />
      </svg>
      {tags.map((t) => (
        <span key={t} className="flex items-center gap-1 rounded-full bg-red-50 py-1 pr-1.5 pl-2.5 text-xs font-medium text-red-700">
          {t}
          <button
            type="button"
            onClick={() => removeTag(t)}
            aria-label={`Remove ${t}`}
            className="flex h-4 w-4 items-center justify-center rounded-full hover:bg-red-100"
          >
            ✕
          </button>
        </span>
      ))}
      <input
        list="area-suggestions"
        value={input}
        onChange={(e) => {
          setInput(e.target.value);
          if (areaOptions.includes(e.target.value)) addTag(e.target.value);
        }}
        onKeyDown={(e) => {
          if (e.key === "Enter") {
            e.preventDefault();
            addTag(input);
          }
        }}
        placeholder={tags.length === 0 ? "Type to add an area…" : ""}
        className="min-w-[140px] flex-1 border-none py-0.5 text-sm text-stone-700 outline-none"
      />
      <datalist id="area-suggestions">
        {areaOptions
          .filter((a) => !tags.includes(a))
          .map((a) => (
            <option key={a} value={a} />
          ))}
      </datalist>
      {tags.map((t) => (
        <input key={t} type="hidden" name="area" value={t} />
      ))}
    </div>
  );
}
