'use client';

import { memo } from 'react';
import { BugStatusBadge } from './BugStatusBadge';
import { BUG_SEVERITY_LABEL, BUG_SEVERITY_COLOR, getBugActualHours } from '@/lib/bug';
import { formatWorkHours } from '@/lib/work-hours';
import { formatDateTimeShort } from '@/lib/format';
import { resolveMemberDisplayName } from '@/lib/member-system';
import { useMemberStore } from '@/stores/useMemberStore';
import type { Bug } from '@/lib/bug';

interface Props {
  bug: Bug;
  testCaseNo?: string;
  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 BugRowImpl({ bug, testCaseNo, onClick }: Props) {
  const actualHours = getBugActualHours(bug);
  const members = useMemberStore((s) => s.members);
  const assigneeName = resolveMemberDisplayName(bug.assigneeId, members);
  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">
      <span className={`h-2 w-2 rounded-full shrink-0 ${PRIORITY_DOT[bug.priority] || 'bg-zinc-300'}`} />
      <span className="text-[11px] font-mono text-[var(--ink-muted)] w-16 shrink-0">{bug.bugNo}</span>
      <span className="text-[13px] text-[var(--ink)] flex-1 truncate">{bug.title}</span>
      <span className={`text-[10px] px-1.5 py-0.5 rounded shrink-0 ${BUG_SEVERITY_COLOR[bug.severity]}`}>{BUG_SEVERITY_LABEL[bug.severity]}</span>
      <BugStatusBadge status={bug.status} />
      <span className="text-[11px] text-[var(--ink-muted)] tabular-nums w-24 text-right shrink-0 whitespace-nowrap" title="计划修复时间">
        {bug.plannedFixAt ? formatDateTimeShort(bug.plannedFixAt) : '待排期'}
      </span>
      {actualHours > 0 && (
        <span className="text-[11px] text-[var(--ink-muted)] tabular-nums w-28 text-right shrink-0 whitespace-nowrap">{formatWorkHours(actualHours)}</span>
      )}
      {testCaseNo && <span className="text-[10px] font-mono text-[var(--ink-muted)] w-14 text-right shrink-0">{testCaseNo}</span>}
      <span className="text-[11px] text-[var(--ink-soft)] w-14 text-right truncate shrink-0">{assigneeName}</span>
    </div>
  );
}

export const BugRow = memo(BugRowImpl);
