import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useBookStore } from '@renderer/stores/useBookStore'
import { useKnowledgeStore } from '@renderer/stores/useKnowledgeStore'
import { useSettingsStore } from '@renderer/stores/useSettingsStore'
import { ipcCall } from '@renderer/lib/ipc-client'
import { NamingCheckModal } from '@renderer/components/ai/NamingCheckModal'
import {
  KnowledgeEditorDialog,
  loadKnowledgeEntries
} from '@renderer/components/knowledge/KnowledgeEditorDialog'

export function KnowledgePanel(): React.JSX.Element {
  const { t } = useTranslation()
  const bookId = useBookStore((s) => s.currentBookId)
  const chapters = useBookStore((s) => s.chapters)
  const selectedChapterId = useBookStore((s) => s.selectedChapterId)
  const extractThreshold = useSettingsStore((s) => s.knowledgeExtractConfidenceThreshold)
  const {
    entries,
    stats,
    tab,
    forgottenOnly,
    editorOpen,
    editingId,
    setTab,
    openEditor,
    closeEditor,
    approve,
    reject,
    deleteEntry,
    batchApprove,
    extractChapter,
    batchApproveHighConfidence
  } = useKnowledgeStore()
  const injectionPreviews = useKnowledgeStore((s) => s.injectionPreviews)
  const loadInjectionPreviews = useKnowledgeStore((s) => s.loadInjectionPreviews)
  const [extracting, setExtracting] = useState(false)
  const [namingOpen, setNamingOpen] = useState(false)
  const [selected, setSelected] = useState<Set<string>>(new Set())
  const [pendingCount, setPendingCount] = useState(0)

  useEffect(() => {
    if (!bookId) return
    void loadKnowledgeEntries(bookId, tab, forgottenOnly).then(({ entries, stats }) => {
      useKnowledgeStore.setState({ entries, stats })
    })
  }, [bookId, tab, forgottenOnly])

  useEffect(() => {
    if (!bookId) return
    void ipcCall(() => window.electronAPI.knowledge.list(bookId, { status: 'pending' })).then(
      (list) => setPendingCount(list.length)
    )
  }, [bookId, entries])

  useEffect(() => {
    if (!bookId || entries.length === 0) return
    void loadInjectionPreviews(
      bookId,
      entries.map((e) => e.id)
    )
  }, [bookId, entries, loadInjectionPreviews])

  const handleBatchApprove = async (): Promise<void> => {
    if (!bookId || selected.size === 0) return
    await batchApprove(bookId, [...selected])
    setSelected(new Set())
  }

  return (
    <>
      <div className="knowledge-panel" data-testid="knowledge-panel">
        <div className="knowledge-toolbar">
          <button
            type="button"
            className="btn btn-primary"
            data-testid="knowledge-new"
            onClick={() => openEditor(null)}
          >
            {t('knowledge.new')}
          </button>
          <button
            type="button"
            className="btn"
            data-testid="naming-check-open"
            onClick={() => setNamingOpen(true)}
          >
            {t('naming.open')}
          </button>
          {tab === 'pending' && bookId && (
            <button
              type="button"
              className="btn"
              data-testid="knowledge-batch-high-confidence"
              onClick={() => void batchApproveHighConfidence(bookId, extractThreshold)}
            >
              {t('knowledge.batchHighConfidence')}
            </button>
          )}
          {bookId && selectedChapterId && (
            <button
              type="button"
              className="btn"
              data-testid="knowledge-extract-current"
              disabled={extracting}
              onClick={() => {
                setExtracting(true)
                void extractChapter(bookId, selectedChapterId).finally(() => setExtracting(false))
              }}
            >
              {extracting ? t('knowledge.extracting') : t('knowledge.extractFromCurrent')}
            </button>
          )}
        </div>
        <div className="knowledge-tabs">
          <button
            type="button"
            className={`kb-tab ${tab === 'pending' ? 'active' : ''}`}
            data-testid="knowledge-tab-pending"
            onClick={() => setTab('pending')}
          >
            {t('knowledge.tab.pending')}
            {pendingCount > 0 && <span className="kb-badge">{pendingCount}</span>}
          </button>
          <button
            type="button"
            className={`kb-tab ${tab === 'all' ? 'active' : ''}`}
            data-testid="knowledge-tab-all"
            onClick={() => setTab('all')}
          >
            {t('knowledge.tab.all')}
          </button>
          <button
            type="button"
            className={`kb-tab ${tab === 'foreshadow' ? 'active' : ''}`}
            data-testid="knowledge-tab-foreshadow"
            onClick={() => setTab('foreshadow')}
          >
            {t('knowledge.tab.foreshadow')}
          </button>
        </div>
        {tab === 'foreshadow' && (
          <div className="knowledge-stats" data-testid="knowledge-foreshadow-stats">
            {t('knowledge.statsSummary', {
              buried: stats.buried,
              resolved: stats.resolved,
              forgotten: stats.forgotten
            })}
          </div>
        )}
        {tab === 'pending' && selected.size > 0 && (
          <button
            type="button"
            className="btn"
            data-testid="knowledge-batch-approve"
            onClick={() => void handleBatchApprove()}
          >
            {t('knowledge.batchApprove', { count: selected.size })}
          </button>
        )}
        <div className="knowledge-list">
          {entries.map((entry) => (
            <div key={entry.id} className="kb-item" data-testid={`knowledge-item-${entry.id}`}>
              {tab === 'pending' && (
                <input
                  type="checkbox"
                  checked={selected.has(entry.id)}
                  onChange={(e) => {
                    const next = new Set(selected)
                    if (e.target.checked) next.add(entry.id)
                    else next.delete(entry.id)
                    setSelected(next)
                  }}
                />
              )}
              <div className="kb-item-main">
                <div className="kb-item-title">
                  {entry.title}
                  {entry.extractionConfidence != null && (
                    <span className="kb-confidence-badge">
                      {Math.round(entry.extractionConfidence * 100)}%
                    </span>
                  )}
                </div>
                <div className="kb-item-meta">
                  {t(`knowledge.type.${entry.type}`)} · {t(`knowledge.status.${entry.status}`)}
                </div>
                {entry.mergeTargetId && (
                  <div
                    className="kb-merge-hint"
                    data-testid={`knowledge-merge-review-${entry.id}`}
                  >
                    {t('knowledge.mergeSuggest', {
                      title:
                        entries.find((e) => e.id === entry.mergeTargetId)?.title ??
                        entry.mergeTargetId
                    })}
                  </div>
                )}
                {entry.content && <div className="kb-item-content">{entry.content}</div>}
                {(injectionPreviews[entry.id]?.length ?? 0) > 0 && (
                  <div
                    className="kb-injection-preview"
                    data-testid={`knowledge-injection-preview-${entry.id}`}
                  >
                    <div className="kb-injection-label">{t('knowledge.injectionPreview')}</div>
                    {injectionPreviews[entry.id]!.map((log) => (
                      <div key={log.id} className="kb-injection-preview-row">
                        {t('knowledge.injectionEntry', {
                          date: new Date(log.injectedAt).toLocaleDateString(),
                          mode: t(`knowledge.injectionMode.${log.flowMode}`),
                          chapter:
                            chapters.find((c) => c.id === log.chapterId)?.title ??
                            t('knowledge.noChapter')
                        })}
                      </div>
                    ))}
                  </div>
                )}
              </div>
              <div className="kb-item-actions">
                {entry.status === 'pending' && bookId && (
                  <>
                    <button
                      type="button"
                      className="btn btn-sm"
                      data-testid={`knowledge-approve-${entry.id}`}
                      onClick={() => void approve(bookId, entry.id)}
                    >
                      {t('knowledge.approve')}
                    </button>
                    <button
                      type="button"
                      className="btn btn-sm"
                      onClick={() => void reject(bookId, entry.id)}
                    >
                      {t('knowledge.reject')}
                    </button>
                  </>
                )}
                <button type="button" className="btn btn-sm" onClick={() => openEditor(entry.id)}>
                  {t('knowledge.edit')}
                </button>
                {bookId && (
                  <button
                    type="button"
                    className="btn btn-sm"
                    onClick={() => void deleteEntry(bookId, entry.id)}
                  >
                    {t('knowledge.delete')}
                  </button>
                )}
              </div>
            </div>
          ))}
          {entries.length === 0 && (
            <div className="sidebar-empty">{t('knowledge.empty')}</div>
          )}
        </div>
      </div>
      <KnowledgeEditorDialog open={editorOpen} entryId={editingId} onClose={closeEditor} />
      <NamingCheckModal open={namingOpen} onClose={() => setNamingOpen(false)} />
    </>
  )
}
