"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Search, TrendingUp, Flame, FileText, X } from "lucide-react";
import { Avatar } from "./Avatar";
import { useClickOutside } from "@/lib/use-click-outside";
import type { Post, User } from "@/lib/types";
import { useTrending } from "@/lib/use-trending";

const CATEGORIES = [
  { label: "Music", bg: "linear-gradient(135deg,#ff3cac,#7b2ff7)" },
  { label: "Design", bg: "linear-gradient(135deg,#00c6ff,#0072ff)" },
  { label: "Gaming", bg: "linear-gradient(135deg,#7b2ff7,#3a1d6e)" },
  { label: "Food", bg: "linear-gradient(135deg,#ff9a3c,#ff3c3c)" },
  { label: "Sports", bg: "linear-gradient(135deg,#2fd573,#0ba864)" },
  { label: "Travel", bg: "linear-gradient(135deg,#00e5ff,#0092b8)" },
];

/**
 * The feed's single search entry point: live people/post results as you
 * type, with trending tags and categories shown underneath.
 */
export function FeedSearchBox() {
  const [q, setQ] = useState("");
  const [open, setOpen] = useState(false);
  const [results, setResults] = useState<{ users: User[]; posts: Post[] }>({
    users: [],
    posts: [],
  });
  const [searching, setSearching] = useState(false);
  const router = useRouter();
  const ref = useClickOutside<HTMLDivElement>(open, () => setOpen(false));
  const inputRef = useRef<HTMLInputElement>(null);
  // Counted from this site's posts. On a new site there are none, and the
  // whole trending block stays out of the way.
  const trending = useTrending(6);

  useEffect(() => {
    const term = q.trim();
    if (term.length < 2) {
      setResults({ users: [], posts: [] });
      return;
    }
    setSearching(true);
    const t = setTimeout(() => {
      fetch(`/api/search?q=${encodeURIComponent(term)}`)
        .then((r) => (r.ok ? r.json() : { users: [], posts: [] }))
        .then((d) => setResults({ users: d.users ?? [], posts: d.posts ?? [] }))
        .catch(() => setResults({ users: [], posts: [] }))
        .finally(() => setSearching(false));
    }, 220);
    return () => clearTimeout(t);
  }, [q]);

  function go(term: string) {
    if (!term.trim()) return;
    setOpen(false);
    setQ("");
    router.push(`/search?q=${encodeURIComponent(term.trim())}`);
  }

  const showResults = q.trim().length >= 2;

  return (
    <div className="relative" ref={ref}>
      <div
        /* fsb-box is what globals.css reaches for to flatten this pill
           when it sits inside the rail's own card. Without the class the
           rule matched nothing, so a white pill sat inside a white card
           and the search read as two stacked cards. */
        className={`fsb-box flex items-center gap-2 rounded-full px-4 py-2.5 border transition-all ${
          open
            ? "bg-white dark:bg-neutral-900 border-fuchsia-400 ring-2 ring-fuchsia-400/25 shadow-sm"
            : "bg-white dark:bg-neutral-900 border-neutral-200 dark:border-neutral-800 hover:border-neutral-300 dark:hover:border-neutral-700"
        }`}
      >
        <Search size={16} className="text-neutral-400 shrink-0" />
        <input
          ref={inputRef}
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onFocus={() => setOpen(true)}
          onKeyDown={(e) => e.key === "Enter" && go(q)}
          placeholder="Search posts, people, sounds..."
          className="flex-1 bg-transparent outline-none text-sm min-w-0"
        />
        {q && (
          <button
            onClick={() => {
              setQ("");
              inputRef.current?.focus();
            }}
            className="text-neutral-400 hover:text-neutral-600 shrink-0"
            title="Clear"
          >
            <X size={14} />
          </button>
        )}
      </div>

      {open && (
        <div className="absolute left-0 right-0 top-full mt-2 z-50 bg-white dark:bg-neutral-900 border border-neutral-200 dark:border-neutral-800 rounded-2xl p-3 shadow-2xl max-h-[70vh] overflow-y-auto">
          {showResults && (
            <div className="mb-4">
              <div className="flex items-center gap-1.5 mb-2 text-xs font-bold text-neutral-500">
                <Search size={12} /> Results
                {searching && <span className="text-neutral-400 font-normal">· searching…</span>}
              </div>

              {results.users.length === 0 && results.posts.length === 0 && !searching && (
                <p className="text-xs text-neutral-400 py-2 px-1">
                  Nothing matched &ldquo;{q.trim()}&rdquo;.
                </p>
              )}

              {results.users.slice(0, 4).map((u) => (
                <Link
                  key={u.id}
                  href={`/${u.username}`}
                  onClick={() => setOpen(false)}
                  className="tt-row"
                >
                  <Avatar user={u} size={30} effect={false} />
                  <span className="flex-1 min-w-0 text-left">
                    <span className="block text-sm font-semibold truncate">{u.name}</span>
                  </span>
                </Link>
              ))}

              {results.posts.slice(0, 3).map((p) => (
                <Link
                  key={p.id}
                  href={`/post/${p.id}`}
                  onClick={() => setOpen(false)}
                  className="tt-row"
                >
                  <span className="tt-rank text-neutral-400">
                    <FileText size={13} />
                  </span>
                  <span className="flex-1 min-w-0 text-left">
                    <span className="block text-[13px] truncate">{p.text}</span>
                    <span className="block text-[11px] text-neutral-400">
                      by @{p.author.username}
                    </span>
                  </span>
                </Link>
              ))}
            </div>
          )}

          {trending.length > 0 && (
            <>
              <div className="flex items-center gap-1.5 mb-2 text-xs font-bold text-neutral-500">
                <TrendingUp size={13} /> Trending now
              </div>
              <div className="flex flex-col mb-4">
                {trending.map((t, i) => (
                  <button key={t.tag} className="tt-row" onClick={() => go(t.tag)}>
                    <span className="tt-rank" style={{ color: i < 3 ? "#ff3c5f" : "#9ca3af" }}>
                      {i + 1}
                    </span>
                    <span className="flex-1 min-w-0 text-left">
                      <span className="block text-sm font-semibold truncate">#{t.tag}</span>
                      <span className="block text-[11px] text-neutral-400">
                        {t.count} post{t.count === 1 ? "" : "s"}
                      </span>
                    </span>
                    {t.count >= 3 && <Flame size={14} className="text-orange-500 shrink-0" />}
                  </button>
                ))}
              </div>
            </>
          )}

          <div className="text-xs font-bold text-neutral-500 mb-2">Browse</div>
          <div className="flex flex-wrap gap-2">
            {CATEGORIES.map((c) => (
              <button
                key={c.label}
                className="tt-chip"
                style={{ background: c.bg }}
                onClick={() => go(c.label)}
              >
                {c.label}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
