import { LocalTask, SubtaskActivity } from '../../../api';
import { parseActivityLog } from '../../../lib/utils';
import { useLocalActivityLog } from '../../../hooks/useTaskDetail';
import { ActivityTimeline } from '../../activity/ActivityTimeline';
import { SubtaskActivitySection } from './SubtaskActivitySection';

interface ProgressTabProps {
  task: LocalTask;
  onViewFullLog: () => void;
  subtaskActivities?: SubtaskActivity[];
}

export function ProgressTab({ task, onViewFullLog, subtaskActivities }: ProgressTabProps) {
  const hasSubtasks = subtaskActivities && subtaskActivities.length > 0;
  const activityLogQuery = useLocalActivityLog(task.id, true);
  const activityLog = activityLogQuery.data ?? '';
  const activityEvents = parseActivityLog(activityLog);
  const logLoading = activityLogQuery.isLoading;

  return (
    <div className="flex flex-col gap-3">
      <div className="bg-white border border-slate-200 rounded-xl p-4 shadow-sm">
        <div className="flex justify-between items-center mb-2">
          <div className="font-bold text-[13px] text-slate-800">実行 Timeline</div>
          <div className="text-2xs text-slate-400">{activityEvents.length} 件</div>
        </div>
        <div className="text-xs text-slate-500 mb-3">
          {task.latestJob?.currentMovement ? `現在: ${task.latestJob.currentMovement}` : '現在の movement は取得待ちです'}
          {task.latestJob?.currentActivity && ['running', 'dispatching'].includes(task.latestJob?.status ?? '') && (
            <div className="text-2xs text-slate-400 mt-0.5 font-mono truncate">
              {task.latestJob.currentActivity}
            </div>
          )}
        </div>
        <ActivityTimeline
          events={activityEvents}
          emptyLabel={logLoading ? '読み込み中...' : 'まだ進行情報がありません。'}
        />
      </div>
      {hasSubtasks && <SubtaskActivitySection subtaskActivities={subtaskActivities!} />}
      <div className="bg-white border border-slate-200 rounded-xl p-4 shadow-sm">
        <div className="flex justify-between items-center mb-3">
          <div className="font-bold text-[13px] text-slate-800">Raw activity.log</div>
          <button onClick={onViewFullLog} className="text-2xs text-blue-600 font-bold hover:underline">全文</button>
        </div>
        <pre className="text-xs whitespace-pre-wrap bg-slate-900 text-slate-100 rounded-xl p-3 min-h-[260px] max-h-[520px] overflow-auto font-mono">
          {logLoading && !activityLog
            ? '(activity.log を読み込み中...)'
            : (activityLog || '(activity.log がまだありません)').slice(-12000)}
        </pre>
      </div>
    </div>
  );
}
