'use client';
/**
 * RecentTasksBar — 底部最近任务横向卡（4个）
 * 任务名 + 状态 + 进度条
 */
import { useEffect } from 'react';
import { useTaskStore } from '@/stores/taskStore';
import { api } from '@/lib/api';
import { TaskListItem, TaskStatus } from '@/types/index';
import { PaginatedResponse } from '@/types/index';
import Link from 'next/link';
import { clsx } from 'clsx';

const STATUS_LABELS: Record<TaskStatus, { label: string; color: string }> = {
  pending: { label: '待开始', color: 'text-text-tertiary' },
  generating: { label: '生成中', color: 'text-status-warning' },
  pending_selection: { label: '待挑选', color: 'text-brand-orange' },
  pending_review: { label: '待审核', color: 'text-status-info' },
  approved: { label: '已通过', color: 'text-status-success' },
  rejected: { label: '已打回', color: 'text-status-error' },
  archived: { label: '已归档', color: 'text-text-tertiary' },
};

export function RecentTasksBar() {
  const { recentTasks, setRecentTasks } = useTaskStore();

  useEffect(() => {
    loadRecent();
  }, []);

  async function loadRecent() {
    try {
      const data = await api.get<PaginatedResponse<TaskListItem>>('/api/v1/tasks?page=1&page_size=4');
      setRecentTasks(data.items);
    } catch {
      // ignore
    }
  }

  if (recentTasks.length === 0) return null;

  return (
    <div>
      <h3 className="text-sm font-medium text-text-secondary mb-3">最近任务</h3>
      <div className="flex gap-3">
        {recentTasks.slice(0, 4).map((task) => {
          const statusInfo = STATUS_LABELS[task.status];
          return (
            <Link key={task.id} href={`/tasks/${task.id}/text`}
              aria-label={`任务：${task.theme}，状态：${statusInfo.label}`}
              className="flex-1 border border-border-default rounded-xl p-3 bg-surface-primary hover:border-brand-orange transition-colors">
              <p className="text-sm font-medium text-text-primary line-clamp-1">{task.theme}</p>
              <span className={clsx('text-xs', statusInfo.color)}>{statusInfo.label}</span>
              {/* 进度条（generating 状态时显示） */}
              {task.status === 'generating' && (
                <div className="mt-2 h-1.5 bg-surface-tertiary rounded-full overflow-hidden">
                  <div className="h-full bg-brand-orange rounded-full animate-pulse w-1/3" aria-hidden="true" />
                </div>
              )}
            </Link>
          );
        })}
      </div>
    </div>
  );
}
