'use client';

import { useState, useMemo } from 'react';
import { X, AlertTriangle, Link2, ChevronRight, Clock, User, Tag, Play, Trash2, ArrowRightLeft, CalendarRange } from 'lucide-react';
import { StatusBadge } from './StatusBadge';
import { CategoryChip } from './CategoryChip';
import { ActivityLogPanel } from '@/components/ActivityLogPanel';
import { useDevTaskStore } from '@/stores/useDevTaskStore';
import { useWorkActivityStore } from '@/stores/useWorkActivityStore';
import { useTaskCategoryStore } from '@/stores/useTaskCategoryStore';
import { useRequirementStore } from '@/stores/useRequirementStore';
import { useMemberStore } from '@/stores/useMemberStore';
import { useAuthStore } from '@/stores/useAuthStore';
import { FilterSelect } from '@/components/FilterSelect';
import { WorkDateTimePicker } from '@/components/WorkDateTimePicker';
import {
  ALLOWED_TRANSITIONS,
  DEV_TASK_STATUS_LABEL,
  DEV_TASK_STATUS_COLOR,
  canStartDevTask,
  formatHours,
  getEstimateHours,
  getActualHours,
  needsDevTaskClaim,
} from '@/lib/dev-task';
import { needsDelayReason } from '@/lib/dev-task-transitions';
import { calcWorkHours, formatShortTime, isoToLocal, localToISO } from '@/lib/work-hours';
import type { DevTaskStatus } from '@/lib/dev-task';

interface Props {
  taskId: string;
  allTaskIds: string[];
  onClose: () => void;
  contextLabel?: string;
  readOnly?: boolean;
}

function defaultPlanStartLocal(): string {
  const d = new Date();
  d.setHours(9, 0, 0, 0);
  return isoToLocal(d.toISOString());
}

function defaultPlanEndLocal(): string {
  const d = new Date();
  d.setHours(18, 0, 0, 0);
  return isoToLocal(d.toISOString());
}

function defaultProgressNextStartLocal(): string {
  const d = new Date();
  d.setDate(d.getDate() + 1);
  d.setHours(9, 30, 0, 0);
  return isoToLocal(d.toISOString());
}

export function DevTaskDetailDrawer({ taskId, allTaskIds, onClose, contextLabel, readOnly = false }: Props) {
  const { tasks, changeStatus, setBlocked, deleteTask, updateTask } = useDevTaskStore();
  const addProgressNote = useWorkActivityStore((s) => s.addProgressNote);
  const { categories } = useTaskCategoryStore();
  const { requirements } = useRequirementStore();
  const { members } = useMemberStore();
  const user = useAuthStore((s) => s.user);
  const [showTransfer, setShowTransfer] = useState(false);
  const [transferTo, setTransferTo] = useState('');
  const [showDelayInput, setShowDelayInput] = useState(false);
  const [delayReason, setDelayReason] = useState('');
  const [showPlanInput, setShowPlanInput] = useState(false);
  const [planStartLocal, setPlanStartLocal] = useState('');
  const [planEndLocal, setPlanEndLocal] = useState('');
  const [progressNote, setProgressNote] = useState('');
  const [progressBlocker, setProgressBlocker] = useState('');
  const [progressHelperId, setProgressHelperId] = useState('');
  const [progressDelayRisk, setProgressDelayRisk] = useState('');
  const [progressNextStartLocal, setProgressNextStartLocal] = useState(() => defaultProgressNextStartLocal());

  const task = tasks.find((t) => t.id === taskId);
  if (!task) return null;

  const category = categories.find((c) => c.id === task.categoryId);
  const requirement = requirements.find((r) => r.id === task.requirementId);
  const allTasks = tasks.filter((t) => allTaskIds.includes(t.id));
  const predecessors = (task.predecessorIds || []).map((id) => allTasks.find((t) => t.id === id)).filter(Boolean);
  const nextStatuses = ALLOWED_TRANSITIONS[task.status] || [];

  const [blockReason, setBlockReason] = useState(task.blockReason || '');
  const [showBlockInput, setShowBlockInput] = useState(false);

  const estimate = useMemo(() => getEstimateHours(task), [task]);
  const executorEstimate = typeof task.estimateHours === 'number' && task.estimateHours > 0 ? task.estimateHours : undefined;
  const aiEstimate = typeof task.aiEstimateHours === 'number' && task.aiEstimateHours > 0 ? task.aiEstimateHours : undefined;
  const actual = useMemo(() => getActualHours(task), [task]);
  const overrun = actual > estimate && estimate > 0;
  const requireDelay = task.status === 'todo' && needsDelayReason(task);
  const currentUserName = user?.name || '';
  const needsClaim = needsDevTaskClaim(task);
  const startReady = canStartDevTask(task);
  const visibleNextStatuses = nextStatuses.filter((status) => status !== 'in_progress' || startReady);
  const planStartISO = localToISO(planStartLocal);
  const planEndISO = localToISO(planEndLocal);
  const planStartBeforeEnd = Boolean(planStartISO && planEndISO && planStartISO < planEndISO);
  const planEstimateHours = planStartBeforeEnd ? calcWorkHours(planStartISO, planEndISO) : 0;
  const progressNextStartISO = localToISO(progressNextStartLocal);
  const canRecordProgress = Boolean(
    (progressNote.trim() || progressBlocker.trim() || progressDelayRisk.trim()) && progressNextStartISO,
  );

  const openPlanInput = () => {
    if (readOnly) return;
    setPlanStartLocal(task.expectedStartAt ? isoToLocal(task.expectedStartAt) : defaultPlanStartLocal());
    setPlanEndLocal(task.expectedEndAt ? isoToLocal(task.expectedEndAt) : defaultPlanEndLocal());
    setShowPlanInput(true);
  };

  const handleSavePlan = () => {
    if (readOnly) return;
    const assigneeId = task.assigneeId || currentUserName;
    if (!assigneeId) {
      alert('领取前需要先登录或选择负责人');
      return;
    }
    if (!planStartBeforeEnd || planEstimateHours <= 0 || !planStartISO || !planEndISO) return;
    updateTask(task.id, {
      assigneeId,
      expectedStartAt: planStartISO,
      expectedEndAt: planEndISO,
      estimateHours: planEstimateHours,
    });
    setShowPlanInput(false);
  };

  const handleTransition = (to: DevTaskStatus) => {
    if (readOnly) return;
    if (to === 'in_progress' && !startReady) {
      openPlanInput();
      return;
    }
    if (to === 'in_progress' && requireDelay && !showDelayInput) {
      setShowDelayInput(true);
      return;
    }
    const opts = to === 'in_progress' && delayReason.trim()
      ? { delayReason: delayReason.trim() }
      : undefined;
    const result = changeStatus(task.id, to, opts);
    if (!result.ok) {
      alert(result.message);
      return;
    }
    if (to === 'in_progress') {
      setShowDelayInput(false);
      setDelayReason('');
    }
  };

  const handleBlock = () => {
    if (readOnly) return;
    if (!blockReason.trim()) return;
    setBlocked(task.id, true, blockReason.trim());
    setShowBlockInput(false);
  };

  const handleUnblock = () => {
    if (readOnly) return;
    setBlocked(task.id, false);
    setBlockReason('');
  };

  const handleProgressNote = () => {
    if (readOnly) return;
    const note = progressNote.trim();
    const blocker = progressBlocker.trim();
    const delayRisk = progressDelayRisk.trim();
    if (!note && !blocker && !delayRisk) return;
    if (!progressNextStartISO) {
      alert('请填写下次开始时间');
      return;
    }

    addProgressNote({
      actorId: task.assigneeId,
      sourceType: 'dev_task',
      sourceId: task.id,
      title: task.title,
      note: note || '今日进展已更新',
      nextStartAt: progressNextStartISO,
      blocker: blocker || undefined,
      helperId: progressHelperId || undefined,
      delayRisk: delayRisk || undefined,
    });
    setProgressNote('');
    setProgressBlocker('');
    setProgressHelperId('');
    setProgressDelayRisk('');
    setProgressNextStartLocal(defaultProgressNextStartLocal());
  };

  return (
    <div className="fixed inset-0 z-50 flex justify-end bg-black/40" onClick={onClose}>
      <div className="flex h-full w-full max-w-xl flex-col border-l border-[var(--line)] bg-[var(--bg)]" onClick={(e) => e.stopPropagation()}>
        {contextLabel && (
          <div className="px-5 py-2 border-b border-[var(--line)] bg-[var(--bg-subtle)] shrink-0">
            <span className="text-[11px] text-[var(--ink-muted)]">{contextLabel}</span>
          </div>
        )}
        <div className="flex items-center justify-between h-14 px-5 border-b border-[var(--line)] bg-[var(--bg-card)] shrink-0">
          <div className="flex min-w-0 flex-1 items-center gap-2 pr-3">
            <span className="shrink-0 text-[12px] font-mono text-[var(--ink-muted)]">{task.taskNo}</span>
            <span className="min-w-0 flex-1 truncate text-[15px] font-semibold text-[var(--ink)]">{task.title}</span>
          </div>
          <div className="flex shrink-0 items-center gap-1">
            {!readOnly && task.status !== 'submitted' && (
              <button onClick={() => setShowTransfer(!showTransfer)} className="p-1.5 rounded-lg hover:bg-blue-50 text-[var(--ink-muted)] hover:text-blue-500" title="转交"><ArrowRightLeft className="h-4 w-4" /></button>
            )}
            {!readOnly && <button onClick={() => { if (confirm('确定删除此任务？')) { deleteTask(task.id); onClose(); } }} className="p-1.5 rounded-lg hover:bg-red-50 text-[var(--ink-muted)] hover:text-red-500" title="删除"><Trash2 className="h-4 w-4" /></button>}
            <button onClick={onClose} className="p-1.5 rounded-lg hover:bg-[var(--bg-subtle)]"><X className="h-4 w-4 text-[var(--ink-muted)]" /></button>
          </div>
        </div>

        {showTransfer && !readOnly && (
          <div className="mx-5 mt-3 rounded-lg border border-[var(--line)] p-3 flex items-center gap-2">
            <span className="text-[11px] text-[var(--ink-muted)] shrink-0">转交给：</span>
            <FilterSelect
              value={transferTo || 'all'}
              onChange={(value) => setTransferTo(value === 'all' ? '' : value)}
              options={members.filter((m) => m.name !== task.assigneeId).map((m) => ({ value: m.name, label: m.name }))}
              allLabel="选择人员"
              className="flex-1"
              labelClassName="max-w-[calc(100%-20px)]"
            />
            <button onClick={() => { if (transferTo) { updateTask(task.id, { assigneeId: transferTo }); setShowTransfer(false); setTransferTo(''); } }} disabled={!transferTo} className="h-7 px-2.5 rounded text-[11px] font-medium bg-blue-500 text-white disabled:opacity-50">确认</button>
            <button onClick={() => setShowTransfer(false)} className="h-7 px-2 text-[11px] text-[var(--ink-muted)]">取消</button>
          </div>
        )}

        <div className="flex-1 space-y-4 overflow-y-auto p-5">

          {requirement && (
            <div className="rounded-lg border border-[var(--line)] bg-[var(--bg-card)] p-4">
              <div className="text-[10px] text-[var(--ink-muted)] uppercase tracking-wide mb-1.5">关联需求</div>
              <div className="flex min-w-0 items-center gap-2">
                <Link2 className="h-3.5 w-3.5 text-[var(--accent)]" />
                <span className="text-[11px] font-mono text-[var(--ink-muted)]">{requirement.code}</span>
                <span className="min-w-0 truncate text-[13px] text-[var(--ink)]">{requirement.title}</span>
              </div>
            </div>
          )}

          <div className="space-y-4 rounded-lg border border-[var(--line)] bg-[var(--bg-card)] p-4">
            <div className="text-[10px] text-[var(--ink-muted)] uppercase tracking-wide">状态 & 操作</div>
            <div className="flex flex-wrap items-center gap-2">
              <span className={`inline-flex items-center rounded-lg px-3 py-1.5 text-[13px] font-semibold ${DEV_TASK_STATUS_COLOR[task.status]}`}>
                {DEV_TASK_STATUS_LABEL[task.status]}
              </span>
              {task.isBlocked && (
                <span className="inline-flex items-center gap-1 text-[11px] text-red-600 bg-red-50 border border-red-200 px-2 py-1 rounded-lg">
                  <AlertTriangle className="h-3 w-3" />阻塞中
                </span>
              )}
              {requireDelay && (
                <span className="inline-flex items-center gap-1 text-[11px] text-orange-600 bg-orange-50 border border-orange-200 px-2 py-1 rounded-lg" title="已超过预计截止时间，开干需填延后原因">
                  <AlertTriangle className="h-3 w-3" />超期未开始
                </span>
              )}
            </div>

            {visibleNextStatuses.length > 0 && !showDelayInput && !readOnly && (
              <div className="flex items-center gap-2 pt-1 flex-wrap">
                <ChevronRight className="h-3.5 w-3.5 text-[var(--ink-muted)]" />
                {visibleNextStatuses.map((s) => (
                  <button key={s} onClick={() => handleTransition(s)} className="h-8 px-4 rounded-lg text-[12px] font-medium bg-[var(--accent)] text-white hover:bg-[var(--accent-hover)] transition-colors">
                    {DEV_TASK_STATUS_LABEL[s]}
                  </button>
                ))}
              </div>
            )}

            {task.status === 'todo' && !startReady && !showPlanInput && !readOnly && (
              <div className="flex items-center gap-2 pt-1">
                <button
                  onClick={openPlanInput}
                  disabled={needsClaim && !currentUserName}
                  className="h-8 px-4 rounded-lg text-[12px] font-medium bg-orange-500 text-white hover:bg-orange-600 disabled:opacity-50"
                >
                  {needsClaim ? '领取并填写计划' : '填写计划'}
                </button>
                <span className="text-[11px] text-[var(--ink-muted)]">
                  {needsClaim ? '领取时必须填写预计开始和预计截止' : '开始开发前需要补齐预计开始和预计截止'}
                </span>
              </div>
            )}

            {showPlanInput && !readOnly && (
              <div className="rounded-lg border border-orange-200 bg-orange-50 p-3 space-y-3">
                <div className="text-[11px] font-medium text-orange-700">
                  {needsClaim ? '领取并填写计划' : '填写计划'}
                </div>
                <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                  <div>
                    <label className="mb-1 block text-[11px] text-orange-700">预计开始</label>
                    <WorkDateTimePicker
                      value={planStartLocal}
                      onChange={setPlanStartLocal}
                      placeholder="选择预计开始"
                      defaultHour={9}
                      className="bg-white"
                    />
                  </div>
                  <div>
                    <label className="mb-1 block text-[11px] text-orange-700">预计截止</label>
                    <WorkDateTimePicker
                      value={planEndLocal}
                      onChange={setPlanEndLocal}
                      placeholder="选择预计截止"
                      defaultHour={18}
                      popoverAlign="right"
                      className="bg-white"
                    />
                  </div>
                </div>
                <div className="flex items-center justify-between gap-2">
                  <span className="text-[11px] text-orange-700">
                    执行预估：{planEstimateHours > 0 ? formatHours(planEstimateHours) : '请选择有效起止时间'}
                  </span>
                  <div className="flex gap-2">
                    <button onClick={handleSavePlan} disabled={!planStartBeforeEnd || planEstimateHours <= 0} className="h-7 px-3 rounded text-[11px] font-medium bg-[var(--accent)] text-white disabled:opacity-50">保存</button>
                    <button onClick={() => setShowPlanInput(false)} className="h-7 px-2 text-[11px] text-orange-700">取消</button>
                  </div>
                </div>
              </div>
            )}

            {showDelayInput && !readOnly && (
              <div className="rounded-lg border border-orange-200 bg-orange-50 p-3 space-y-2">
                <div className="flex items-center gap-1.5 text-[11px] text-orange-700">
                  <AlertTriangle className="h-3.5 w-3.5" />
                  已超过预计截止时间，请说明延后原因
                </div>
                <input value={delayReason} onChange={(e) => setDelayReason(e.target.value)} placeholder="延后原因（必填）" className="h-8 w-full rounded-md border border-orange-200 bg-white px-2 text-[12px] focus:border-orange-400 focus:outline-none" autoFocus />
                <div className="flex gap-2">
                  <button onClick={() => handleTransition('in_progress')} disabled={!delayReason.trim()} className="h-7 px-3 rounded text-[11px] font-medium bg-[var(--accent)] text-white disabled:opacity-50">开始开发</button>
                  <button onClick={() => { setShowDelayInput(false); setDelayReason(''); }} className="h-7 px-2 text-[11px] text-[var(--ink-muted)]">取消</button>
                </div>
              </div>
            )}

            <div className="pt-2 border-t border-[var(--line)]">
              {task.isBlocked ? (
                <div className="space-y-2">
                  <div className="flex items-start gap-1.5 text-[12px] text-red-600 bg-red-50 rounded-lg px-3 py-2">
                    <AlertTriangle className="h-3.5 w-3.5 shrink-0 mt-0.5" />
                    <span>{task.blockReason}</span>
                  </div>
                  {!readOnly && <button onClick={handleUnblock} className="text-[11px] text-emerald-600 font-medium hover:underline">解除阻塞</button>}
                </div>
              ) : (
                showBlockInput && !readOnly ? (
                  <div className="flex gap-2">
                    <input value={blockReason} onChange={(e) => setBlockReason(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') handleBlock(); }} placeholder="阻塞原因" className="flex-1 h-8 rounded-lg border border-[var(--line)] px-3 text-[12px] focus:border-red-400 focus:outline-none" autoFocus />
                    <button onClick={handleBlock} disabled={!blockReason.trim()} className="h-8 px-3 rounded-lg text-[11px] font-medium bg-red-500 text-white disabled:opacity-50">确认</button>
                    <button onClick={() => setShowBlockInput(false)} className="h-8 px-2 text-[11px] text-[var(--ink-muted)]">取消</button>
                  </div>
                ) : (
                  !readOnly && <button onClick={() => setShowBlockInput(true)} className="text-[11px] text-red-500 font-medium hover:underline">标记阻塞</button>
                )
              )}
            </div>
          </div>

          {task.status !== 'todo' && task.status !== 'submitted' && !readOnly && (
            <div className="space-y-4 rounded-lg border border-[var(--line)] bg-[var(--bg-card)] p-4">
              <div className="text-[10px] text-[var(--ink-muted)] uppercase tracking-wide">今日进展</div>
              <textarea
                value={progressNote}
                onChange={(e) => setProgressNote(e.target.value)}
                placeholder="今日完成内容、剩余内容"
                rows={3}
                className="w-full resize-none rounded-lg border border-[var(--line)] bg-[var(--bg)] px-3 py-2 text-[12px] leading-5 text-[var(--ink)] focus:border-[var(--accent)] focus:outline-none"
              />
              <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
                <input
                  value={progressBlocker}
                  onChange={(e) => setProgressBlocker(e.target.value)}
                  placeholder="阻塞原因"
                  className="h-8 rounded-lg border border-[var(--line)] bg-[var(--bg)] px-2 text-[12px] focus:border-orange-400 focus:outline-none"
                />
                <FilterSelect
                  value={progressHelperId || 'all'}
                  onChange={(value) => setProgressHelperId(value === 'all' ? '' : value)}
                  options={members.filter((m) => m.name !== task.assigneeId).map((m) => ({ value: m.name, label: m.name }))}
                  allLabel="协助人"
                  className="w-full"
                  labelClassName="max-w-[calc(100%-20px)]"
                />
              </div>
              <input
                value={progressDelayRisk}
                onChange={(e) => setProgressDelayRisk(e.target.value)}
                placeholder="延期风险"
                className="h-8 w-full rounded-lg border border-[var(--line)] bg-[var(--bg)] px-2 text-[12px] focus:border-orange-400 focus:outline-none"
              />
              <div className="grid grid-cols-[minmax(0,1fr)_auto] items-end gap-2">
                <div>
                  <label className="mb-1 flex items-center gap-1 text-[11px] text-[var(--ink-muted)]">
                    下次开始时间
                    <span className="text-red-500">*</span>
                  </label>
                  <WorkDateTimePicker
                    value={progressNextStartLocal}
                    onChange={setProgressNextStartLocal}
                    placeholder="选择下次开始时间"
                    defaultHour={9}
                    popoverAlign="right"
                    className="bg-[var(--bg)]"
                  />
                </div>
                <button
                  onClick={handleProgressNote}
                  disabled={!canRecordProgress}
                  className="h-9 px-3 rounded-lg text-[12px] font-medium bg-[var(--accent)] text-white hover:bg-[var(--accent-hover)] disabled:opacity-50"
                >
                  记录进展
                </button>
              </div>
            </div>
          )}

          <div className="rounded-lg border border-[var(--line)] bg-[var(--bg-card)] p-4">
            <div className="text-[10px] text-[var(--ink-muted)] uppercase tracking-wide mb-3 flex items-center gap-1.5"><CalendarRange className="h-3 w-3" />时间信息</div>
            <div className="grid grid-cols-1 gap-2 text-[12px] sm:grid-cols-2 sm:gap-x-4 [&>div]:min-w-0 [&>div]:rounded-md [&>div]:bg-[var(--bg-subtle)] [&>div]:px-3 [&>div]:py-2">
              <div className="flex flex-col gap-0.5">
                <span className="text-[10px] text-[var(--ink-muted)]">预计开始</span>
                <span className="text-[var(--ink)] font-medium tabular-nums">{task.expectedStartAt ? formatShortTime(task.expectedStartAt) : '-'}</span>
              </div>
              <div className="flex flex-col gap-0.5">
                <span className="text-[10px] text-[var(--ink-muted)]">预计截止</span>
                <span className="text-[var(--ink)] font-medium tabular-nums">{task.expectedEndAt ? formatShortTime(task.expectedEndAt) : '-'}</span>
              </div>
              <div className="flex flex-col gap-0.5">
                <span className="text-[10px] text-[var(--ink-muted)]">实际开始</span>
                <span className="text-[var(--ink)] font-medium tabular-nums">{task.actualStartAt ? formatShortTime(task.actualStartAt) : '—'}</span>
              </div>
              <div className="flex flex-col gap-0.5">
                <span className="text-[10px] text-[var(--ink-muted)]">实际结束</span>
                <span className="text-[var(--ink)] font-medium tabular-nums">{task.actualEndAt ? formatShortTime(task.actualEndAt) : '—'}</span>
              </div>
              <div className="flex flex-col gap-0.5">
                <span className="text-[10px] text-[var(--ink-muted)]">AI 预估</span>
                <span className="text-[var(--ink)] font-medium tabular-nums">{aiEstimate ? formatHours(aiEstimate) : '—'}</span>
              </div>
              <div className="flex flex-col gap-0.5">
                <span className="text-[10px] text-[var(--ink-muted)]">执行预估</span>
                <span className="text-[var(--ink)] font-medium tabular-nums">{executorEstimate ? formatHours(executorEstimate) : '待负责人填写'}</span>
              </div>
              <div className="flex flex-col gap-0.5">
                <span className="text-[10px] text-[var(--ink-muted)]">实际耗时</span>
                <span className={`font-medium tabular-nums ${actual > 0 ? (overrun ? 'text-red-600' : (actual < estimate ? 'text-emerald-600' : 'text-[var(--ink)]')) : 'text-[var(--ink-muted)]'}`}>
                  {actual > 0 ? formatHours(actual) : '—'}
                  {task.actualStartAt && !task.actualEndAt && <span className="text-[10px] ml-1 text-[var(--ink-muted)]">进行中</span>}
                </span>
              </div>
            </div>
            {task.delayReason && (
              <div className="mt-3 pt-3 border-t border-[var(--line)] text-[11px] text-orange-700 bg-orange-50 rounded-lg px-3 py-2">
                <div className="flex items-start gap-1.5">
                  <AlertTriangle className="h-3 w-3 shrink-0 mt-0.5" />
                  <div><span className="font-medium">延后原因：</span>{task.delayReason}</div>
                </div>
              </div>
            )}
            {task.overdueVersionReason && (
              <div className="mt-2 text-[11px] text-orange-700 bg-orange-50 rounded-lg px-3 py-2">
                <span className="font-medium">超出版本截止原因：</span>{task.overdueVersionReason}
              </div>
            )}
          </div>

          <div className="rounded-lg border border-[var(--line)] bg-[var(--bg-card)] p-4">
            <div className="text-[10px] text-[var(--ink-muted)] uppercase tracking-wide mb-3">基本信息</div>
            <div className="grid grid-cols-1 gap-2 text-[12px] sm:grid-cols-2 sm:gap-x-4 [&>div]:min-w-0 [&>div]:rounded-md [&>div]:bg-[var(--bg-subtle)] [&>div]:px-3 [&>div]:py-2">
              <div className="flex items-center gap-2">
                <Tag className="h-3 w-3 text-[var(--ink-muted)]" />
                <span className="text-[var(--ink-muted)]">类型</span>
                <CategoryChip category={category} />
              </div>
              <div className="flex items-center gap-2">
                <User className="h-3 w-3 text-[var(--ink-muted)]" />
                <span className="text-[var(--ink-muted)]">负责人</span>
                <span className={`font-medium ${needsClaim ? 'text-orange-600' : 'text-[var(--ink)]'}`}>{needsClaim ? '待领取' : task.assigneeId}</span>
              </div>
              <div className="flex items-center gap-2">
                <span className="text-[var(--ink-muted)]">优先级</span>
                <span className="text-[var(--ink)] font-medium">{task.priority}</span>
              </div>
              <div className="flex items-center gap-2">
                <Clock className="h-3 w-3 text-[var(--ink-muted)]" />
                <span className="text-[var(--ink-muted)]">创建</span>
                <span className="text-[var(--ink)]">{formatShortTime(task.createdAt)}</span>
              </div>
            </div>
            {task.description && (
              <div className="mt-3 pt-3 border-t border-[var(--line)]">
                <p className="text-[12px] text-[var(--ink-soft)] leading-relaxed">{task.description}</p>
              </div>
            )}
          </div>

          <ActivityLogPanel sourceType="dev_task" sourceId={task.id} />

          {predecessors.length > 0 && (
            <div className="rounded-lg border border-[var(--line)] bg-[var(--bg-card)] p-4">
              <div className="text-[10px] text-[var(--ink-muted)] uppercase tracking-wide mb-2">前置任务</div>
              <div className="space-y-2">
                {predecessors.map((p: any) => (
                  <div key={p.id} className="flex items-center gap-2 text-[12px] px-2.5 py-1.5 rounded-lg bg-[var(--bg-subtle)]">
                    <Link2 className="h-3 w-3 text-[var(--ink-muted)]" />
                    <span className="font-mono text-[var(--ink-muted)]">{p.taskNo}</span>
                    <span className="text-[var(--ink)] flex-1 truncate">{p.title}</span>
                    <StatusBadge status={p.status} />
                  </div>
                ))}
              </div>
            </div>
          )}

        </div>
      </div>
    </div>
  );
}
