import { knowledgeAreas, processGroups } from '@/data'
import { getProcessesByKaAndPg } from '@/utils/practice'
import { ProcessCell } from './ProcessCell'
import { useLongPress } from '@/hooks/useLongPress'
import clsx from 'clsx'

interface PracticeMatrixProps {
  answeredCells: Map<string, boolean>
  currentCellId: string | null
  showAnswerForCell: { cellId: string; answer: string; expiresAt: number } | null
  onLongPress: (cellId: string) => void
  onLongPressEnd: () => void
  onCellClick: (cellId: string) => void
  getCellTabIndex: (cellId: string) => number
}

interface KnowledgeAreaCellProps {
  ka: any
  isAnswered: boolean
  isFocused: boolean
  showAnswer?: string | null
  onLongPress: (cellId: string) => void
  onLongPressEnd: () => void
  onClick: (cellId: string) => void
  tabIndex: number
}

function KnowledgeAreaCell({
  ka,
  isAnswered,
  isFocused,
  showAnswer,
  onLongPress,
  onLongPressEnd,
  onClick,
  tabIndex,
}: KnowledgeAreaCellProps) {
  const cellId = `ka-${ka.id}`
  const longPressHandlers = useLongPress(cellId, {
    onLongPress,
    onLongPressEnd,
  })

  return (
    <td
      data-cell-id={cellId}
      className={clsx(
        'sticky left-0 z-10 p-2 border border-gray-200 dark:border-gray-700 font-medium cursor-pointer transition-all duration-200',
        isFocused && 'ring-2 ring-blue-500 ring-inset',
        !isAnswered && 'border-dashed'
      )}
      style={{
        backgroundColor: isAnswered ? `${ka.color}15` : 'transparent',
        borderLeftWidth: 4,
        borderLeftColor: isFocused ? '#3b82f6' : ka.color,
      }}
      onClick={() => onClick(cellId)}
      tabIndex={tabIndex}
      role="button"
      aria-label={`知识领域：${ka.name}`}
      {...longPressHandlers}
    >
      {isAnswered ? (
        <div className="flex items-center gap-2">
          <span className="font-bold text-xs" style={{ color: ka.color }}>
            {ka.order}
          </span>
          <span className="text-xs text-gray-900 dark:text-white">
            {ka.name}
          </span>
        </div>
      ) : (
        <div className="min-h-[24px]" />
      )}

      {/* 长按显示答案 */}
      {showAnswer && (
        <div className="absolute inset-0 flex items-center justify-center bg-black/80 rounded z-20">
          <span className="text-white text-sm font-medium px-2 text-center">
            {showAnswer}
          </span>
        </div>
      )}
    </td>
  )
}

export function PracticeMatrix({
  answeredCells,
  currentCellId,
  showAnswerForCell,
  onLongPress,
  onLongPressEnd,
  onCellClick,
  getCellTabIndex,
}: PracticeMatrixProps) {
  const sortedKAs = [...knowledgeAreas].sort((a, b) => a.order - b.order)
  const sortedPGs = [...processGroups].sort((a, b) => a.order - b.order)

  return (
    <div className="overflow-x-auto">
      <table className="w-full border-collapse min-w-[900px]">
        {/* 表头：过程组 */}
        <thead>
          <tr>
            <th className="sticky left-0 z-10 bg-gray-100 dark:bg-gray-800 p-2 text-left text-xs font-semibold text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-gray-700 min-w-[120px]">
              知识领域 / 过程组
            </th>
            {sortedPGs.map((pg) => (
              <th
                key={pg.id}
                className="p-2 text-center text-xs font-semibold text-white border border-gray-200 dark:border-gray-700 min-w-[120px]"
                style={{ backgroundColor: pg.color }}
              >
                {pg.name}
              </th>
            ))}
          </tr>
        </thead>

        {/* 表体：知识领域 × 过程 */}
        <tbody>
          {sortedKAs.map((ka) => {
            const kaCellId = `ka-${ka.id}`
            return (
              <tr key={ka.id}>
                {/* 知识领域名称 */}
                <KnowledgeAreaCell
                  ka={ka}
                  isAnswered={answeredCells.get(kaCellId) || false}
                  isFocused={currentCellId === kaCellId}
                  showAnswer={
                    showAnswerForCell?.cellId === kaCellId
                      ? showAnswerForCell.answer
                      : null
                  }
                  onLongPress={onLongPress}
                  onLongPressEnd={onLongPressEnd}
                  onClick={onCellClick}
                  tabIndex={getCellTabIndex(kaCellId)}
                />

                {/* 每个过程组的单元格 */}
                {sortedPGs.map((pg) => {
                  const processes = getProcessesByKaAndPg(ka.id, pg.id)

                  return (
                    <td
                      key={pg.id}
                      className="p-2 border border-gray-200 dark:border-gray-700 align-top bg-white dark:bg-gray-800"
                    >
                      <div className="space-y-1">
                        {processes.map((p) => {
                          const processCellId = `process-${p.id}`

                          return (
                            <ProcessCell
                              key={p.id}
                              process={p}
                              isAnswered={answeredCells.get(processCellId) || false}
                              isFocused={currentCellId === processCellId}
                              showAnswer={
                                showAnswerForCell?.cellId === processCellId
                                  ? showAnswerForCell.answer
                                  : null
                              }
                              onLongPress={onLongPress}
                              onLongPressEnd={onLongPressEnd}
                              onClick={onCellClick}
                              tabIndex={getCellTabIndex(processCellId)}
                            />
                          )
                        })}
                      </div>
                    </td>
                  )
                })}
              </tr>
            )
          })}
        </tbody>
      </table>
    </div>
  )
}
