import {
  ArrowLeftIcon,
  ArrowRightIcon,
  ChevronRightIcon,
  SearchIcon,
} from "lucide-react"
import { useEffect, useMemo, useRef, useState } from "react"
import Wrap from "@/components/wrap"
import { ARTICLES, type Article, CATEGORIES } from "@/lib/models/article"
import { cn } from "@/lib/utils"

export default function HelpPage() {
  const [search, setSearch] = useState("")
  const [activeCategoryId, setActiveCategoryId] = useState<number | null>(null)
  const [selectedArticle, setSelectedArticle] = useState<Article | null>(null)

  const filtered = useMemo(() => {
    let list = ARTICLES

    if (activeCategoryId !== null) {
      list = list.filter(a => a.catalogId === activeCategoryId)
    }

    if (search.trim()) {
      const kw = search.trim().toLowerCase()
      list = list.filter(
        a =>
          a.title.toLowerCase().includes(kw) ||
          a.keyword.toLowerCase().includes(kw) ||
          a.content.toLowerCase().includes(kw),
      )
    }

    return list
  }, [search, activeCategoryId])

  const currentIndex = selectedArticle
    ? filtered.findIndex(a => a.id === selectedArticle.id)
    : -1

  const prevArticle = currentIndex > 0 ? filtered[currentIndex - 1] : null
  const nextArticle =
    currentIndex >= 0 && currentIndex < filtered.length - 1
      ? filtered[currentIndex + 1]
      : null

  const handleArticleClick = (article: Article) => {
    setSelectedArticle(article)
  }

  const handleBack = () => {
    setSelectedArticle(null)
  }

  const activeCategory = CATEGORIES.find(c => c.id === activeCategoryId)

  return (
    <div className="min-h-[calc(100vh-5rem)] bg-gray-50">
      <Wrap className="pt-28 pb-16">
        <div className="max-w-2xl mx-auto mb-10">
          <div className="relative">
            <SearchIcon className="absolute left-4 top-1/2 -translate-y-1/2 size-5 text-gray-400" />
            <input
              type="text"
              placeholder="请输入想要了解的关键词"
              className="w-full pl-12 pr-24 py-3.5 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent shadow-sm bg-white text-sm"
              value={search}
              onChange={e => {
                setSearch(e.target.value)
                setSelectedArticle(null)
              }}
            />
            <button className="absolute right-2 top-1/2 -translate-y-1/2 px-6 py-2 bg-blue-600 text-white text-sm rounded-lg hover:bg-blue-700 transition">
              搜索
            </button>
          </div>
        </div>

        <div className="flex gap-8">
          <aside className="w-52 shrink-0">
            <nav className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden sticky top-28">
              <div className="px-5 py-4 border-b border-gray-100">
                <h3 className="font-semibold text-gray-800">帮助分类</h3>
              </div>
              <ul>
                <li>
                  <button
                    onClick={() => {
                      setActiveCategoryId(null)
                      setSelectedArticle(null)
                    }}
                    className={cn(
                      "w-full text-left px-5 py-3 text-sm transition-colors flex items-center justify-between",
                      activeCategoryId === null
                        ? "bg-blue-50 text-blue-600 font-medium"
                        : "text-gray-600 hover:bg-gray-50",
                    )}
                  >
                    全部文章
                    <ChevronRightIcon className="size-4" />
                  </button>
                </li>
                {CATEGORIES.map(cat => (
                  <li key={cat.id}>
                    <button
                      onClick={() => {
                        setActiveCategoryId(cat.id)
                        setSelectedArticle(null)
                      }}
                      className={cn(
                        "w-full text-left px-5 py-3 text-sm transition-colors flex items-center justify-between",
                        activeCategoryId === cat.id
                          ? "bg-blue-50 text-blue-600 font-medium"
                          : "text-gray-600 hover:bg-gray-50",
                      )}
                    >
                      {cat.name}
                      <ChevronRightIcon className="size-4" />
                    </button>
                  </li>
                ))}
              </ul>
            </nav>
          </aside>

          <main className="flex-1 min-w-0">
            {selectedArticle ? (
              <ArticleDetail
                article={selectedArticle}
                prev={prevArticle}
                next={nextArticle}
                onPrev={
                  prevArticle
                    ? () => handleArticleClick(prevArticle)
                    : undefined
                }
                onNext={
                  nextArticle
                    ? () => handleArticleClick(nextArticle)
                    : undefined
                }
                onBack={handleBack}
                categoryName={activeCategory?.name}
              />
            ) : (
              <ArticleList
                articles={filtered}
                search={search}
                categoryName={activeCategory?.name}
                onArticleClick={handleArticleClick}
              />
            )}
          </main>
        </div>
      </Wrap>
    </div>
  )
}

function ArticleList({
  articles,
  search,
  categoryName,
  onArticleClick,
}: {
  articles: Article[]
  search: string
  categoryName?: string
  onArticleClick: (article: Article) => void
}) {
  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-8">
      <h2 className="text-lg font-semibold text-gray-800 mb-6">
        {search
          ? `搜索"${search}"的结果`
          : categoryName
            ? categoryName
            : "全部文章"}
        <span className="text-sm font-normal text-gray-400 ml-2">
          共 {articles.length} 篇
        </span>
      </h2>

      {articles.length === 0 ? (
        <div className="text-center py-16 text-gray-400">
          <SearchIcon className="size-12 mx-auto mb-4 opacity-30" />
          <p>未找到相关文章，请尝试其他关键词</p>
        </div>
      ) : (
        <ul className="divide-y divide-gray-100">
          {articles.map(article => (
            <li key={article.id}>
              <button
                onClick={() => onArticleClick(article)}
                className="w-full text-left py-4 px-2 -mx-2 rounded-lg hover:bg-gray-50 transition-colors group flex items-center justify-between"
              >
                <span className="text-sm text-gray-700 group-hover:text-blue-600 transition-colors pr-4">
                  {article.title}
                </span>
                <span className="text-xs text-gray-400 whitespace-nowrap shrink-0">
                  {article.createTime}
                </span>
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}

function ArticleDetail({
  article,
  prev,
  next,
  onPrev,
  onNext,
  onBack,
  categoryName,
}: {
  article: Article
  prev: Article | null
  next: Article | null
  onPrev?: () => void
  onNext?: () => void
  onBack: () => void
  categoryName?: string
}) {
  const contentRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (contentRef.current) {
      contentRef.current.innerHTML = article.content
    }
  }, [article.content])

  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-8">
      <nav className="flex items-center gap-2 text-sm text-gray-400 mb-6">
        <button
          onClick={onBack}
          className="hover:text-blue-600 transition-colors"
        >
          帮助中心
        </button>
        {categoryName && (
          <>
            <ChevronRightIcon className="size-3" />
            <span>{categoryName}</span>
          </>
        )}
        <ChevronRightIcon className="size-3" />
        <span className="text-gray-600 truncate">{article.title}</span>
      </nav>
      <h1 className="text-xl font-bold text-gray-900 mb-3">{article.title}</h1>
      <p className="text-xs text-gray-400 mb-8">{article.createTime}</p>
      <div
        ref={contentRef}
        className="prose prose-sm max-w-none text-gray-700 leading-relaxed [&_h3]:text-lg [&_h3]:font-semibold [&_h3]:text-gray-800 [&_h3]:mt-6 [&_h3]:mb-3 [&_h4]:text-base [&_h4]:font-medium [&_h4]:text-gray-800 [&_h4]:mt-4 [&_h4]:mb-2 [&_p]:mb-3 [&_pre]:bg-gray-50 [&_pre]:p-4 [&_pre]:rounded-lg [&_pre]:text-sm [&_code]:bg-gray-100 [&_code]:px-1.5 [&_code]:py-0.5 [&_code]:rounded [&_code]:text-sm [&_strong]:text-gray-800"
      />
      <div className="mt-12 pt-6 border-t border-gray-100 flex items-center justify-between">
        <div className="flex-1 min-w-0">
          {prev ? (
            <button
              onClick={onPrev}
              className="text-sm text-gray-500 hover:text-blue-600 transition-colors flex items-center gap-1 max-w-full"
            >
              <ArrowLeftIcon className="size-3.5 shrink-0" />
              <span className="truncate">上一条：{prev.title}</span>
            </button>
          ) : (
            <span className="text-sm text-gray-300">已是第一篇</span>
          )}
        </div>
        <div className="flex-1 min-w-0 text-right">
          {next ? (
            <button
              onClick={onNext}
              className="text-sm text-gray-500 hover:text-blue-600 transition-colors flex items-center gap-1 justify-end max-w-full"
            >
              <span className="truncate">下一条：{next.title}</span>
              <ArrowRightIcon className="size-3.5 shrink-0" />
            </button>
          ) : (
            <span className="text-sm text-gray-300">已是最后一篇</span>
          )}
        </div>
      </div>
      <div className="mt-6 text-center">
        <button
          onClick={onBack}
          className="inline-flex items-center gap-1 text-sm text-blue-600 hover:text-blue-700 transition-colors"
        >
          <ArrowLeftIcon className="size-3.5" />
          返回列表
        </button>
      </div>
    </div>
  )
}
