import { LocalTask, SubtaskActivity } from '../../../api';
import { useTranslation } from 'react-i18next';
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 { t } = useTranslation('detail');
  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 data-testid="progress-tab" className="flex flex-col gap-3">
      <div className="bg-canvas 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">{t('progress.timeline')}</div>
          <div className="text-2xs text-slate-400">{activityEvents.length} {t('progress.events')}</div>
        </div>
        <div className="text-xs text-slate-500 mb-3">
          {task.latestJob?.currentMovement ? t('progress.current', { movement: task.latestJob.currentMovement }) : t('progress.currentPending')}
          {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 ? t('progress.loading') : t('progress.noProgress')}
        />
      </div>
      {hasSubtasks && <SubtaskActivitySection subtaskActivities={subtaskActivities!} />}
      <div className="bg-canvas 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">{t('progress.viewFull')}</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
            ? t('progress.logLoading')
            : (activityLog || t('progress.logEmpty')).slice(-12000)}
        </pre>
      </div>
    </div>
  );
}
