// src/pages/agent-office/components/TaskTab.jsx
import { useState, useEffect } from 'react';
import { getAgentTasks } from '../../../api';

const STATUS_STYLE = {
  succeeded: { bg: '#065f46', fg: '#34d399' },
  failed:    { bg: '#7f1d1d', fg: '#fca5a5' },
  working:   { bg: '#1e3a5f', fg: '#60a5fa' },
  pending:   { bg: '#92400e', fg: '#fbbf24' },
  approved:  { bg: '#065f46', fg: '#34d399' },
  rejected:  { bg: '#7f1d1d', fg: '#fca5a5' }
};

// result_data는 백엔드에서 dict 또는 string 둘 다 올 수 있다.
// React child로 직접 못 그리는 객체는 stringify, string은 parse 시도 후 pretty,
// 둘 다 안 되면 원본 문자열을 그대로 표시.
function formatResultData(rd) {
  if (rd == null) return '';
  if (typeof rd === 'object') {
    try { return JSON.stringify(rd, null, 2); }
    catch { return String(rd); }
  }
  if (typeof rd === 'string') {
    try { return JSON.stringify(JSON.parse(rd), null, 2); }
    catch { return rd; }
  }
  return String(rd);
}

function formatTime(ts) {
  if (!ts) return '';
  const d = new Date(ts);
  const now = new Date();
  const isToday = d.toDateString() === now.toDateString();
  const time = d.toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit' });
  return isToday ? time : `${d.getMonth() + 1}/${d.getDate()} ${time}`;
}

export default function TaskTab({ agentId, refreshTrigger }) {
  const [tasks, setTasks] = useState([]);
  const [expanded, setExpanded] = useState(null);

  useEffect(() => {
    let cancelled = false;
    getAgentTasks(agentId, 20).then(data => {
      if (!cancelled) setTasks(Array.isArray(data) ? data : (data?.tasks || []));
    });
    return () => { cancelled = true; };
  }, [agentId, refreshTrigger]);

  return (
    <div className="ao-task-tab">
      {tasks.length === 0 && <div className="ao-empty">No tasks yet</div>}
      {tasks.map(task => {
        const style = STATUS_STYLE[task.status] || STATUS_STYLE.pending;
        return (
          <div key={task.id} className="ao-task-item" onClick={() => setExpanded(expanded === task.id ? null : task.id)}>
            <div className="ao-task-header">
              <span className="ao-task-type">{task.task_type}</span>
              <span className="ao-task-badge" style={{ background: style.bg, color: style.fg }}>{task.status}</span>
              <span className="ao-task-time">{formatTime(task.created_at)}</span>
            </div>
            {expanded === task.id && task.result_data && (
              <pre className="ao-task-result">
                {formatResultData(task.result_data)}
              </pre>
            )}
          </div>
        );
      })}
    </div>
  );
}
