// frontend/src/pages/PipelineHistory.jsx
import { useState, useEffect } from 'react';
import { useAuth } from '../context/AuthContext.jsx';
import { useT } from '../i18n/translations.js';
import { api } from '../context/AuthContext.jsx';
import { Card, StatusBadge, Spinner } from '../components/ui/index.jsx';
import { formatDistanceToNow, format } from 'date-fns';
import { Zap } from 'lucide-react';

export default function PipelineHistory() {
  const { user } = useAuth();
  const t = useT(user?.locale);
  const [runs, setRuns] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.get('/pipeline/history?limit=50').then(({ data }) => {
      setRuns(data);
      setLoading(false);
    });
  }, []);

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-semibold text-gray-900">Pipeline History</h1>
      {loading ? (
        <div className="flex justify-center py-16"><Spinner size={32} /></div>
      ) : runs.length === 0 ? (
        <Card className="p-12 text-center">
          <Zap size={32} className="text-gray-300 mx-auto mb-3" />
          <p className="text-gray-500 text-sm">No pipeline runs yet</p>
        </Card>
      ) : (
        <Card className="overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-gray-100 bg-gray-50">
                {['Status', 'Triggered by', 'Scripts', 'Duration', 'Date'].map(h => (
                  <th key={h} className="text-left px-4 py-3 text-xs font-medium text-gray-500 uppercase tracking-wide">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {runs.map(run => {
                const duration = run.started_at && run.completed_at
                  ? Math.round((new Date(run.completed_at) - new Date(run.started_at)) / 1000)
                  : null;
                return (
                  <tr key={run.id} className="hover:bg-gray-50">
                    <td className="px-4 py-3"><StatusBadge status={run.status} /></td>
                    <td className="px-4 py-3 text-gray-600 capitalize">{run.triggered_by}</td>
                    <td className="px-4 py-3 text-gray-900 font-medium">{run.scripts_count || 0}</td>
                    <td className="px-4 py-3 text-gray-500">{duration ? `${Math.floor(duration/60)}m ${duration%60}s` : '—'}</td>
                    <td className="px-4 py-3 text-gray-400 text-xs">
                      {formatDistanceToNow(new Date(run.created_at), { addSuffix: true })}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>
      )}
    </div>
  );
}
