import { useEffect, useMemo, useState } from 'react'
import { FixedSizeList } from 'react-window'
import { coarseLabel, decodedLabel, pct, searchedLabel } from './model.js'

function useListHeight() {
  const getHeight = () => Math.max(360, window.innerHeight - 312)
  const [height, setHeight] = useState(getHeight)
  useEffect(() => {
    const onResize = () => setHeight(getHeight())
    window.addEventListener('resize', onResize)
    return () => window.removeEventListener('resize', onResize)
  }, [])
  return height
}

function QueryRow({ item, latest, selected, onSelect, style }) {
  const canSelect = Boolean(latest)
  return (
    <div style={style}>
      <button
        className={`qrow query-select-row ${item.keep === false ? 'drop' : 'keep'} ${selected ? 'selected' : ''}`}
        disabled={!canSelect}
        title={item.reason || ''}
        type="button"
        onClick={() => canSelect && onSelect?.(item, latest)}
      >
        <span className="qmark">{item.keep === false ? '✕' : '✓'}</span>
        {typeof item.valid === 'number' && (
          <span className={`qvalid ${item.valid >= 6 ? 'ok' : 'low'}`}>语义{item.valid}</span>
        )}
        <span className="qtext">{item.query}</span>
        {latest ? (
          <>
            <span className="qcreation searched">{searchedLabel(latest)}</span>
            <span className="qcreation knowledge">{coarseLabel(latest)}</span>
            <span className="qcreation decoded">{decodedLabel(latest)}</span>
          </>
        ) : (
          <span className="qdetail">未搜索</span>
        )}
      </button>
    </div>
  )
}

export default function QueryColumn({
  familyItems,
  latestByQuery,
  selectedQuery,
  onSelect,
  familyRunCount,
  totalRunCount,
  totalItemCount,
  emptyMessage,
}) {
  const height = useListHeight()
  const itemData = useMemo(() => ({
    familyItems,
    latestByQuery,
    selectedQuery,
    onSelect,
  }), [familyItems, latestByQuery, selectedQuery, onSelect])

  return (
    <div className="axcol qcol">
      <div className="axhd qhd">
        <div className="axis-title">
          <span className="query-search-icon">⌕</span>
          <span>Query 词</span>
        </div>
        <span className="qhd-metrics">
          <span className="run-progress">执行进度 {pct(totalRunCount, totalItemCount)}%</span>
          <span className="gn">{familyRunCount}/{familyItems.length}</span>
        </span>
      </div>
      {familyItems.length ? (
        <FixedSizeList
          className="axlist virtual-query-list"
          height={height}
          itemCount={familyItems.length}
          itemData={itemData}
          itemKey={(index, data) => `${data.familyItems[index]?.query}-${index}`}
          itemSize={32}
          width="100%"
        >
          {({ index, style, data }) => {
            const item = data.familyItems[index]
            const latest = data.latestByQuery.get(item.query)
            return (
              <QueryRow
                item={item}
                latest={latest}
                selected={data.selectedQuery?.query_id === latest?.query_id}
                onSelect={data.onSelect}
                style={style}
              />
            )
          }}
        </FixedSizeList>
      ) : (
        <div className="query-column-empty">{emptyMessage || '暂无 Query'}</div>
      )}
    </div>
  )
}
