'use client';

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

interface Props {
  testCase: TestCase;
  category?: TaskCategory;
  categoryLabelWidthEm?: number;
  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, categoryLabelWidthEm, bugCount, onClick }: Props) {
  const estimateHours = getTestCaseEstimateHours(testCase);
  const actualHours = getTestCaseActualHours(testCase);
  const needsClaim = needsTestCaseClaim(testCase);
  const labelWidthStyle = categoryLabelWidthEm ? { width: `${categoryLabelWidthEm}em` } : undefined;
  const hasExecutorEstimate = typeof testCase.estimateHours === 'number' && testCase.estimateHours > 0;
  const hasAiEstimate = typeof testCase.aiEstimateHours === 'number' && testCase.aiEstimateHours > 0;
  const estimatePrefix = hasExecutorEstimate ? '执行预' : hasAiEstimate ? 'AI预' : '预';
  const planText = testCase.plannedTestAt && testCase.plannedEndAt
    ? `${formatDateTimeShort(testCase.plannedTestAt)} → ${formatDateTimeShort(testCase.plannedEndAt)}`
    : testCase.plannedTestAt ? formatDateTimeShort(testCase.plannedTestAt) : '';
  return (
    <div onClick={onClick} className={`px-4 py-2 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' : ''}`}>
      <div className="flex min-w-0 items-start gap-2">
        <span className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${PRIORITY_DOT[testCase.priority] || 'bg-zinc-300'}`} />
        <span className="mt-0.5 w-14 shrink-0 text-[11px] font-mono text-[var(--ink-muted)]">{testCase.caseNo}</span>
        <div className="min-w-0 flex-1">
          <div className="flex min-w-0 items-center gap-1.5">
            <span className="truncate text-[13px] font-medium leading-5 text-[var(--ink)]">{testCase.title}</span>
            <span className="ml-auto inline-flex min-w-0 shrink-0 flex-wrap items-center justify-end gap-x-2.5 gap-y-1 text-[11px]">
              {planText && (
                <span className="tabular-nums whitespace-nowrap text-[var(--ink-muted)]" title="计划测试时间">{planText}</span>
              )}
              <span className="tabular-nums whitespace-nowrap text-[var(--ink-muted)]">
                {actualHours > 0 ? `${formatWorkHours(actualHours)} / ${formatWorkHours(estimateHours)}` : `${estimatePrefix} ${formatWorkHours(estimateHours)}`}
              </span>
            </span>
          </div>
          <div className="mt-1 flex min-w-0 flex-wrap items-center justify-end gap-x-2.5 gap-y-1 text-[11px]">
            {bugCount > 0 && (
              <span className="inline-flex h-5 shrink-0 items-center whitespace-nowrap rounded bg-red-50 px-1.5 text-[10px] font-medium text-red-500">{bugCount} Bug</span>
            )}
            {testCase.aiDraft && (
              <span
                className="inline-flex h-5 shrink-0 items-center justify-center whitespace-nowrap rounded bg-purple-100 px-1.5 text-[10px] font-medium text-purple-600"
                style={labelWidthStyle}
                title="AI 拆解草案，编辑后会移除标记"
              >
                AI 草案
              </span>
            )}
            {!needsClaim && (
              <span className="max-w-[140px] truncate whitespace-nowrap text-[var(--ink-soft)]">负责人：{testCase.assigneeId}</span>
            )}
            {needsClaim ? (
              <span
                className="inline-flex h-5 shrink-0 items-center justify-center whitespace-nowrap rounded bg-orange-50 px-1.5 text-[10px] font-medium text-orange-600"
                style={labelWidthStyle}
              >
                待领取
              </span>
            ) : (
              <TestCaseStatusBadge status={testCase.status} widthEm={categoryLabelWidthEm} />
            )}
            <span
              className="inline-flex h-5 shrink-0 items-center justify-center rounded px-1.5 text-[10px] font-medium whitespace-nowrap"
              style={{
                ...(categoryLabelWidthEm ? { width: `${categoryLabelWidthEm}em` } : {}),
                backgroundColor: category?.color ? `${category.color}15` : 'var(--bg-subtle)',
                color: category?.color || 'var(--ink-soft)',
              }}
              title={category?.name || '未分类'}
            >
              {category?.name || '未分类'}
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}

export const TestCaseRow = memo(TestCaseRowImpl);
