"use client";

import { useEffect, useState, useMemo, useRef } from "react";
import { createPortal } from "react-dom";
import { AnimatePresence, motion } from "framer-motion";
import { Search, X } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useVoteStore } from "@/lib/store";
import { TAG_LABEL, type Artist } from "@/types/artist";

function formatVotes(v: number): string {
  if (v >= 10_000) return `${(v / 10_000).toFixed(1)}w`;
  return v.toLocaleString();
}
import ArtistPortrait from "./cards/ArtistPortrait";
import { cn } from "@/lib/cn";

interface SearchModalProps {
  open: boolean;
  onClose: () => void;
}

export default function SearchModal({ open, onClose }: SearchModalProps) {
  const router = useRouter();
  const [query, setQuery] = useState("");
  const [activeIndex, setActiveIndex] = useState(0);
  const [mounted, setMounted] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const listRef = useRef<HTMLDivElement>(null);

  useEffect(() => setMounted(true), []);

  // 打开时重置 + 自动聚焦 + 锁滚
  useEffect(() => {
    if (!open) return;
    setQuery("");
    setActiveIndex(0);
    const t = setTimeout(() => inputRef.current?.focus(), 80);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      clearTimeout(t);
      document.body.style.overflow = prev;
    };
  }, [open]);

  // 订阅 store 拿活的票数 / rank（投票后立即反映）
  const storeArtists = useVoteStore((s) => s.artists);

  // 过滤艺人：名字 / 编号 / 座右铭 / 标签。默认显示真实 Top12（有票才上榜）
  const results = useMemo<Artist[]>(() => {
    const q = query.trim().toLowerCase();
    if (!q) {
      const top12 = storeArtists.filter((a) => a.votes > 0).slice(0, 12);
      // 还没产生 Top12 时退回到默认 12 位（按编号），保持空态可浏览
      return top12.length > 0 ? top12 : storeArtists.slice(0, 12);
    }
    return storeArtists
      .filter((a) => {
        const tagText = a.tags.map((t) => TAG_LABEL[t]).join("");
        return (
          a.name.toLowerCase().includes(q) ||
          a.enName.toLowerCase().includes(q) ||
          a.no.includes(q) ||
          (a.motto?.toLowerCase().includes(q) ?? false) ||
          tagText.includes(q)
        );
      })
      .slice(0, 20);
  }, [query, storeArtists]);

  // 键盘导航
  useEffect(() => {
    if (!open) return;
    const handler = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        onClose();
      } else if (e.key === "ArrowDown") {
        e.preventDefault();
        setActiveIndex((i) => Math.min(i + 1, results.length - 1));
      } else if (e.key === "ArrowUp") {
        e.preventDefault();
        setActiveIndex((i) => Math.max(i - 1, 0));
      } else if (e.key === "Enter") {
        e.preventDefault();
        const target = results[activeIndex];
        if (target) {
          router.push(`/artist/${target.id}`);
          onClose();
        }
      }
    };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [open, onClose, results, activeIndex, router]);

  // 选中项变化时滚动到可视范围
  useEffect(() => {
    if (!listRef.current) return;
    const el = listRef.current.querySelector(
      `[data-index="${activeIndex}"]`,
    ) as HTMLElement | null;
    el?.scrollIntoView({ block: "nearest" });
  }, [activeIndex]);

  // query 变化时重置高亮
  useEffect(() => {
    setActiveIndex(0);
  }, [query]);

  if (!mounted) return null;

  return createPortal(
    <AnimatePresence>
      {open && (
        <motion.div
          key="search-modal"
          className="fixed inset-0 z-[100] flex items-center justify-center px-4"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.18 }}
        >
          {/* 黑色透明遮罩（点击关闭） · 视觉规范：rgba(0,0,0,0.75) + blur */}
          <button
            type="button"
            aria-label="关闭搜索"
            onClick={onClose}
            className="absolute inset-0 bg-black/75 backdrop-blur-md cursor-default"
          />

          {/* 弹窗主体：居中固定在遮罩层上 */}
          <motion.div
            role="dialog"
            aria-label="搜索艺人"
            className="relative w-full max-w-xl bg-elevated/95 backdrop-blur-xl border border-white/14 rounded-2xl shadow-[0_24px_80px_rgba(0,0,0,0.7),0_0_40px_rgba(139,92,246,0.18)] overflow-hidden"
            initial={{ opacity: 0, scale: 0.94 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.96 }}
            transition={{ duration: 0.22, ease: [0.22, 1, 0.36, 1] }}
          >
            {/* 顶部紫色光条 */}
            <div className="absolute top-0 left-0 right-0 h-0.5 bg-grad-purple" />

            {/* 输入框 */}
            <div className="flex items-center gap-3 px-5 py-4 border-b border-white/[0.06]">
              <Search size={18} className="text-purple-300/80 flex-shrink-0" />
              <input
                ref={inputRef}
                type="search"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="搜索艺人 · 名称 / 编号 / 标签…"
                className="flex-1 bg-transparent border-none outline-none text-white placeholder-white/35 text-base"
              />
              <button
                type="button"
                onClick={onClose}
                aria-label="关闭"
                className="text-white/55 hover:text-white"
              >
                <X size={18} />
              </button>
            </div>

            {/* 结果列表 */}
            <div
              ref={listRef}
              className="max-h-[55vh] sm:max-h-[400px] overflow-y-auto py-2"
            >
              {results.length === 0 ? (
                <EmptyState query={query} />
              ) : (
                <>
                  {!query && (
                    <div className="px-5 pt-1 pb-2">
                      <p className="font-label text-[10px] tracking-widest uppercase text-purple-300/70">
                        {results.some((a) => a.votes > 0)
                          ? "热门艺人 · TOP 12"
                          : "推荐艺人 · 编号顺序"}
                      </p>
                    </div>
                  )}
                  {results.map((a, i) => (
                    <ResultRow
                      key={a.id}
                      artist={a}
                      active={i === activeIndex}
                      index={i}
                      onHover={() => setActiveIndex(i)}
                      onClick={onClose}
                    />
                  ))}
                </>
              )}
            </div>

            {/* 底部结果计数 */}
            <div className="hidden sm:flex items-center justify-end px-5 py-2 border-t border-white/[0.06] text-[11px] text-white/40 bg-deep/40">
              <span className="font-mono">共 {results.length} 个结果</span>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>,
    document.body,
  );
}

function ResultRow({
  artist,
  active,
  index,
  onHover,
  onClick,
}: {
  artist: Artist;
  active: boolean;
  index: number;
  onHover: () => void;
  onClick: () => void;
}) {
  const inTop12 = artist.rank <= 12 && artist.votes > 0;
  return (
    <Link
      data-index={index}
      href={`/artist/${artist.id}`}
      onClick={onClick}
      onMouseEnter={onHover}
      className={cn(
        "flex items-center gap-3 px-5 py-2.5 transition-colors",
        active ? "bg-purple-500/15" : "hover:bg-white/[0.04]",
      )}
    >
      <div className="w-10 h-10 rounded-lg overflow-hidden border border-white/15 flex-shrink-0">
        <ArtistPortrait
          artist={artist}
          rounded="rounded-none"
          className="w-full h-full"
        />
      </div>

      <div className="flex-1 min-w-0">
        <div className="flex items-baseline gap-1.5 text-sm">
          <span className="font-display text-[10px] text-purple-300/80 tabular-nums">
            No.{artist.no}
          </span>
          <span className="font-semibold text-white truncate">
            {artist.name}
          </span>
          <span className="text-white/55 text-xs truncate">
            · {artist.enName}
          </span>
        </div>
        {artist.motto && (
          <div className="text-[11px] text-white/45 truncate italic">
            “{artist.motto}”
          </div>
        )}
      </div>

      <div className="flex-shrink-0 text-right">
        <div
          className={cn(
            "font-display text-xs tabular-nums",
            inTop12 ? "text-purple-300" : "text-white/40",
          )}
        >
          #{artist.rank}
        </div>
        <div className="text-[10px] text-white/35 tabular-nums">
          {formatVotes(artist.votes)} 票
        </div>
      </div>
    </Link>
  );
}

function EmptyState({ query }: { query: string }) {
  return (
    <div className="py-12 px-5 text-center">
      <div className="w-12 h-12 rounded-full bg-white/[0.04] border border-white/10 mx-auto mb-3 flex items-center justify-center text-white/35">
        <Search size={18} />
      </div>
      <p className="text-sm text-white/65">
        未找到匹配 <b className="text-purple-300">「{query}」</b> 的艺人
      </p>
      <p className="text-[11px] text-white/40 mt-1">
        试试改用艺人编号 / 英文名 / 中文名 / 标签关键词
      </p>
    </div>
  );
}
