import { useEffect, useState } from 'react';
import { api, errorMessage } from '../api.js';

export function Operations() {
  const [audit, setAudit] = useState([]);
  const [history, setHistory] = useState([]);
  const [error, setError] = useState('');

  async function load() {
    setError('');
    try {
      const [auditResult, historyResult] = await Promise.all([
        api.get('/operations/audit'),
        api.get('/operations/history'),
      ]);
      setAudit(auditResult.data);
      setHistory(historyResult.data);
    } catch (requestError) {
      setError(errorMessage(requestError));
    }
  }

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

  return (
    <section className="space-y-5">
      <div className="border-b border-zinc-800 pb-5">
        <h1 className="text-2xl font-semibold text-zinc-100">Operations</h1>
      </div>
      {error ? <div className="rounded-md border border-red-900 bg-red-950/50 px-4 py-3 text-sm text-red-200">{error}</div> : null}
      <Table
        columns={['Time', 'Type', 'Node', 'VM', 'Status', 'Duration', 'Snapshot', 'Agent Job']}
        rows={history.map((row) => [
          formatTime(row.startedAt),
          row.type,
          row.nodeName,
          row.vmName,
          row.error || row.status,
          formatDuration(row.durationMs),
          row.snapshotId || '-',
          row.agentJobId || '-',
        ])}
        title="Job History"
      />
      <Table
        columns={['Time', 'User', 'Action', 'Target', 'Details']}
        rows={audit.map((row) => [
          formatTime(row.createdAt),
          row.username || 'system',
          row.action,
          `${row.targetType}${row.targetId ? `:${row.targetId}` : ''}`,
          JSON.stringify(row.details || {}),
        ])}
        title="Audit Log"
      />
    </section>
  );
}

function Table({ columns, rows, title }) {
  return (
    <section className="overflow-hidden rounded-md border border-zinc-800 bg-zinc-900/70">
      <div className="border-b border-zinc-800 px-4 py-3">
        <h2 className="text-sm font-semibold">{title}</h2>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full min-w-[820px] text-left text-sm">
          <thead className="border-b border-zinc-800 text-xs uppercase text-zinc-500">
            <tr>{columns.map((column) => <th className="px-4 py-3 font-medium" key={column}>{column}</th>)}</tr>
          </thead>
          <tbody className="divide-y divide-zinc-800">
            {rows.map((row, index) => (
              <tr key={index}>
                {row.map((cell, cellIndex) => <td className="px-4 py-3 text-zinc-300" key={cellIndex}>{cell}</td>)}
              </tr>
            ))}
            {!rows.length ? <tr><td className="px-4 py-8 text-center text-zinc-500" colSpan={columns.length}>No entries.</td></tr> : null}
          </tbody>
        </table>
      </div>
    </section>
  );
}

function formatTime(value) {
  if (!value) return '-';
  return new Intl.DateTimeFormat(undefined, { dateStyle: 'short', timeStyle: 'medium' }).format(new Date(value));
}

function formatDuration(value) {
  if (!value) return '-';
  const seconds = Math.round(Number(value) / 1000);
  if (seconds < 60) return `${seconds}s`;
  return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
}
