import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useBookStore } from '@renderer/stores/useBookStore'
import { useKnowledgeStore } from '@renderer/stores/useKnowledgeStore'
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 {
    entries,
    stats,
    tab,
    forgottenOnly,
    editorOpen,
    editingId,
    setTab,
    openEditor,
    closeEditor,
    approve,
    reject,
    deleteEntry,
    batchApprove
  } = useKnowledgeStore()
  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])

  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>
        </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}</div>
                <div className="kb-item-meta">
                  {t(`knowledge.type.${entry.type}`)} · {t(`knowledge.status.${entry.status}`)}
                </div>
                {entry.content && <div className="kb-item-content">{entry.content}</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)} />
    </>
  )
}
