'use client';

import { memo } from 'react';
import { TestCaseStatusBadge } from './TestCaseStatusBadge';
import { getTestCaseActualHours, getTestCaseEstimateHours } from '@/lib/test-case';
import { formatWorkHours } from '@/lib/work-hours';
import { CategoryChip } from '@/components/dev-task/CategoryChip';
import type { TestCase } from '@/lib/test-case';
import type { TaskCategory } from '@/lib/task-category';

interface Props {
  testCase: TestCase;
  category?: TaskCategory;
  bugCount: number;
  onClick?: () => void;
}

const PRIORITY_DOT: Record<string, string> = {
  P0: 'bg-red-500',
  P1: 'bg-orange-400',
  P2: 'bg-blue-400',
  P3: 'bg-zinc-300',
};

function TestCaseRowImpl({ testCase, category, bugCount, onClick }: Props) {
  const estimateHours = getTestCaseEstimateHours(testCase);
  const actualHours = getTestCaseActualHours(testCase);
  const hasExecutorEstimate = typeof testCase.estimateHours === 'number' && testCase.estimateHours > 0;
  const hasAiEstimate = typeof testCase.aiEstimateHours === 'number' && testCase.aiEstimateHours > 0;
  const estimatePrefix = hasExecutorEstimate ? '执行预' : hasAiEstimate ? 'AI预' : '预';
  return (
    <div onClick={onClick} className={`flex items-center gap-3 px-4 py-2.5 border-b border-[var(--line)] hover:bg-[var(--bg-subtle)] cursor-pointer transition-colors last:border-b-0 ${testCase.aiDraft ? 'border-l-2 border-l-purple-400 bg-purple-50/30' : ''}`}>
      <span className={`h-2 w-2 rounded-full shrink-0 ${PRIORITY_DOT[testCase.priority] || 'bg-zinc-300'}`} />
      <span className="text-[11px] font-mono text-[var(--ink-muted)] w-14 shrink-0">{testCase.caseNo}</span>
      <div className="flex-1 min-w-0 flex items-center gap-1.5">
        <span className="text-[13px] text-[var(--ink)] truncate">{testCase.title}</span>
        <CategoryChip category={category} />
        {testCase.aiDraft && (
          <span className="text-[10px] text-purple-600 bg-purple-100 px-1.5 py-0.5 rounded shrink-0" title="AI 拆解草案，编辑后会移除标记">
            AI 草案
          </span>
        )}
      </div>
      <TestCaseStatusBadge status={testCase.status} />
      <span className="text-[11px] text-[var(--ink-muted)] tabular-nums w-32 text-right shrink-0 whitespace-nowrap">
        {actualHours > 0 ? `${formatWorkHours(actualHours)} / ${formatWorkHours(estimateHours)}` : `${estimatePrefix} ${formatWorkHours(estimateHours)}`}
      </span>
      {bugCount > 0 && (
        <span className="text-[10px] text-red-500 bg-red-50 px-1.5 py-0.5 rounded shrink-0">{bugCount} Bug</span>
      )}
      <span className="text-[11px] text-[var(--ink-soft)] w-14 text-right truncate shrink-0">{testCase.assigneeId || '-'}</span>
    </div>
  );
}

export const TestCaseRow = memo(TestCaseRowImpl);
