"use client";

import { useState, useEffect } from "react";
import { X, Plus, Loader2 } from "lucide-react";
import { slugify } from "@/lib/types";

interface Tag { id: string; title: string; slug: string }
interface Props {
  value: string[];
  onChange: (tagIds: string[]) => void;
}

export function TagsInput({ value, onChange }: Props) {
  const [allTags, setAllTags] = useState<Tag[]>([]);
  const [loading, setLoading] = useState(true);
  const [input, setInput] = useState("");

  useEffect(() => {
    fetch("/api/admin/tags")
      .then((r) => r.json())
      .then(setAllTags)
      .finally(() => setLoading(false));
  }, []);

  const selectedTags = allTags.filter((t) => value.includes(t.id));
  const suggestions = allTags.filter(
    (t) => !value.includes(t.id) && t.title.toLowerCase().includes(input.toLowerCase())
  );

  async function addTag(title: string) {
    const slug = slugify(title);
    const res = await fetch("/api/admin/tags", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ title, slug }),
    });
    const tag = await res.json();
    if (!allTags.find((t) => t.id === tag.id)) {
      setAllTags((prev) => [...prev, tag]);
    }
    onChange([...value, tag.id]);
    setInput("");
  }

  function removeTag(id: string) {
    onChange(value.filter((v) => v !== id));
  }

  return (
    <div className="space-y-2">
      <div className="flex flex-wrap gap-2 min-h-10 rounded-lg border border-border bg-surface p-2">
        {selectedTags.map((tag) => (
          <span
            key={tag.id}
            className="flex items-center gap-1 rounded-full bg-accent/10 px-2.5 py-1 text-xs font-medium text-accent border border-accent/20"
          >
            {tag.title}
            <button type="button" onClick={() => removeTag(tag.id)}>
              <X size={10} />
            </button>
          </span>
        ))}
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === "Enter" && input.trim()) {
              e.preventDefault();
              const existing = allTags.find((t) => t.title.toLowerCase() === input.toLowerCase());
              if (existing && !value.includes(existing.id)) {
                onChange([...value, existing.id]);
                setInput("");
              } else if (!existing) {
                addTag(input.trim());
              }
            }
          }}
          placeholder={loading ? "در حال بارگذاری..." : "تگ جدید + Enter"}
          className="min-w-32 flex-1 bg-transparent text-sm text-text-primary placeholder:text-text-secondary focus:outline-none"
        />
        {loading && <Loader2 size={14} className="animate-spin text-text-secondary" />}
      </div>

      {input && suggestions.length > 0 && (
        <div className="rounded-lg border border-border bg-surface shadow-lg overflow-hidden">
          {suggestions.slice(0, 5).map((tag) => (
            <button
              key={tag.id}
              type="button"
              onClick={() => { onChange([...value, tag.id]); setInput(""); }}
              className="flex w-full items-center gap-2 px-3 py-2 text-sm text-text-secondary hover:bg-surface-hover hover:text-text-primary"
            >
              <Plus size={12} />
              {tag.title}
            </button>
          ))}
          {!suggestions.find((t) => t.title.toLowerCase() === input.toLowerCase()) && (
            <button
              type="button"
              onClick={() => addTag(input.trim())}
              className="flex w-full items-center gap-2 px-3 py-2 text-sm text-accent hover:bg-accent/10"
            >
              <Plus size={12} />
              ایجاد «{input}»
            </button>
          )}
        </div>
      )}
    </div>
  );
}
