/**
 * CodeEditorWorkflowsPage
 * 
 * Lists CodeEditor workflows for the current feature instance.
 * Uses the codeeditor-specific API endpoint instead of the generic /api/workflows/.
 */

import React, { useState, useEffect, useCallback } from 'react';
import { useCurrentInstance } from '../../../hooks/useCurrentInstance';
import api from '../../../api';
import styles from './CodeEditor.module.css';

interface WorkflowItem {
  id: string;
  label?: string;
  status?: string;
  workflowMode?: string;
  startedAt?: number;
  lastActivity?: number;
}

export const CodeEditorWorkflowsPage: React.FC = () => {
  const { instance } = useCurrentInstance();
  const instanceId = instance?.id || '';
  const [workflows, setWorkflows] = useState<WorkflowItem[]>([]);
  const [loading, setLoading] = useState(false);

  const loadWorkflows = useCallback(() => {
    if (!instanceId) return;
    setLoading(true);
    api.get(`/api/codeeditor/${instanceId}/workflows`)
      .then(res => {
        const items = res.data?.items || res.data?.workflows || [];
        setWorkflows(Array.isArray(items) ? items : []);
      })
      .catch(err => console.error('Failed to load workflows:', err))
      .finally(() => setLoading(false));
  }, [instanceId]);

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

  return (
    <div className={styles.workflowsPage}>
      <div className={styles.workflowsHeader}>
        <h3>CodeEditor Workflows</h3>
        <button className={styles.refreshButton} onClick={loadWorkflows} disabled={loading}>
          {loading ? 'Loading...' : 'Refresh'}
        </button>
      </div>

      {workflows.length === 0 ? (
        <div className={styles.emptyState}>
          {loading ? 'Loading workflows...' : 'No workflows yet. Start a conversation in the Editor view.'}
        </div>
      ) : (
        <table className={styles.workflowTable}>
          <thead>
            <tr>
              <th>Label</th>
              <th>Status</th>
              <th>Started</th>
              <th>Last Activity</th>
            </tr>
          </thead>
          <tbody>
            {workflows.map(wf => (
              <tr key={wf.id}>
                <td>{wf.label || wf.id.slice(0, 8)}</td>
                <td>
                  <span className={`${styles.statusBadge} ${styles[`status_${wf.status || 'unknown'}`]}`}>
                    {wf.status || 'unknown'}
                  </span>
                </td>
                <td>{wf.startedAt ? new Date(wf.startedAt * 1000).toLocaleString() : '-'}</td>
                <td>{wf.lastActivity ? new Date(wf.lastActivity * 1000).toLocaleString() : '-'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      )}
    </div>
  );
};
