import { motion } from 'framer-motion'
import clsx from 'clsx'
import type { Process } from '@/types/itto'
import { useLongPress } from '@/hooks/useLongPress'
import { knowledgeAreaMap } from '@/data'

interface ProcessCellProps {
  process: Process
  isAnswered: boolean
  isFocused: boolean
  showAnswer?: string | null
  onLongPress: (cellId: string) => void
  onLongPressEnd: () => void
  onClick: (cellId: string) => void
  tabIndex: number
}

export function ProcessCell({
  process,
  isAnswered,
  isFocused,
  showAnswer,
  onLongPress,
  onLongPressEnd,
  onClick,
  tabIndex,
}: ProcessCellProps) {
  const cellId = `process-${process.id}`
  const ka = knowledgeAreaMap.get(process.knowledgeAreaId)

  const longPressHandlers = useLongPress(cellId, {
    onLongPress,
    onLongPressEnd,
  })

  return (
    <motion.div
      data-cell-id={cellId}
      className={clsx(
        'relative rounded-lg p-2 transition-all duration-200 cursor-pointer',
        'border-2 focus:outline-none',
        isAnswered
          ? 'bg-white dark:bg-gray-800 border-solid border-gray-300 dark:border-gray-600'
          : 'border-dashed border-gray-300 dark:border-gray-600',
        isFocused && 'ring-2 ring-blue-500 border-blue-500',
        !isAnswered && 'min-h-[40px]'
      )}
      onClick={() => onClick(cellId)}
      tabIndex={tabIndex}
      role="button"
      aria-label={`过程：${process.name}`}
      aria-describedby="hint-info"
      aria-current={isFocused ? 'true' : undefined}
      {...longPressHandlers}
      initial={{ opacity: 0, scale: 0.95 }}
      animate={{ opacity: 1, scale: 1 }}
      transition={{ duration: 0.15 }}
    >
      {isAnswered && (
        <div className="flex items-center gap-1.5">
          <span
            className="inline-block px-1 py-0.5 rounded text-white font-medium shrink-0"
            style={{ backgroundColor: ka?.color, fontSize: '9px' }}
          >
            {process.code}
          </span>
          <span className="text-gray-900 dark:text-gray-100 text-xs">
            {process.name}
          </span>
        </div>
      )}

      {/* 长按显示答案 */}
      {showAnswer && (
        <motion.div
          className="absolute inset-0 flex items-center justify-center bg-black/80 rounded-lg z-10"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
        >
          <span className="text-white text-sm font-medium px-2 text-center">
            {showAnswer}
          </span>
        </motion.div>
      )}
    </motion.div>
  )
}
