'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="px-4 py-2 border-b border-[var(--line)] hover:bg-[var(--bg-subtle)] cursor-pointer transition-colors last:border-b-0">
      <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[bug.priority] || 'bg-zinc-300'}`} />
        <span className="mt-0.5 w-16 shrink-0 text-[11px] font-mono text-[var(--ink-muted)]">{bug.bugNo}</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)]">{bug.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]">
              <span className="tabular-nums whitespace-nowrap text-[var(--ink-muted)]" title="计划修复时间">
                {bug.plannedFixAt ? formatDateTimeShort(bug.plannedFixAt) : '待排期'}
              </span>
              {actualHours > 0 && (
                <span className="tabular-nums whitespace-nowrap text-[var(--ink-muted)]">实际 {formatWorkHours(actualHours)}</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]">
            <span className={`shrink-0 rounded px-1.5 py-0.5 text-[10px] ${BUG_SEVERITY_COLOR[bug.severity]}`}>{BUG_SEVERITY_LABEL[bug.severity]}</span>
            <BugStatusBadge status={bug.status} />
            <span className="max-w-[120px] truncate whitespace-nowrap text-[var(--ink-soft)]">{assigneeName}</span>
            {testCaseNo && <span className="font-mono text-[10px] text-[var(--ink-muted)]">{testCaseNo}</span>}
          </div>
        </div>
      </div>
    </div>
  );
}

export const BugRow = memo(BugRowImpl);
