'use client';

import { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import { PageHeader } from '@bytelyst/dashboard-components';
import { useAuth } from '@/lib/auth-context';
import { listJobs, type FleetJob } from '@/lib/fleet-client';

const STAGES = [
  '',
  'queued',
  'blocked',
  'assigned',
  'building',
  'review',
  'testing',
  'shipped',
  'failed',
  'dead_letter',
];
const POLL_INTERVAL = 30_000;

export default function FleetJobsPage() {
  const { token } = useAuth();
  const [jobs, setJobs] = useState<FleetJob[]>([]);
  const [stage, setStage] = useState('');
  const [loading, setLoading] = useState(true);

  const refresh = useCallback(async () => {
    try {
      const params: Record<string, string> = { limit: '50' };
      if (stage) params.stage = stage;
      const res = await listJobs(params as never);
      setJobs(res.jobs);
    } catch {
      /* degrade */
    } finally {
      setLoading(false);
    }
  }, [stage]);

  useEffect(() => {
    if (!token) return;
    refresh();
    const id = setInterval(refresh, POLL_INTERVAL);
    return () => clearInterval(id);
  }, [token, refresh]);

  return (
    <div className="p-6 space-y-6">
      <PageHeader title="Fleet Jobs" />

      {/* Filters */}
      <div className="flex gap-3 items-center">
        <label htmlFor="stage-filter" className="text-sm font-medium">
          Stage:
        </label>
        <select
          id="stage-filter"
          value={stage}
          onChange={e => setStage(e.target.value)}
          className="rounded border px-2 py-1 text-sm bg-background"
          aria-label="Filter by stage"
        >
          {STAGES.map(s => (
            <option key={s} value={s}>
              {s || 'All'}
            </option>
          ))}
        </select>
      </div>

      {/* Table */}
      {loading ? (
        <p className="text-muted-foreground">Loading jobs...</p>
      ) : jobs.length === 0 ? (
        <p className="text-muted-foreground">No jobs match the current filter.</p>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full text-sm" aria-label="Fleet jobs table">
            <thead>
              <tr className="border-b text-left text-muted-foreground">
                <th className="pb-2 pr-4">Idempotency Key</th>
                <th className="pb-2 pr-4">Stage</th>
                <th className="pb-2 pr-4">Priority</th>
                <th className="pb-2 pr-4">Kind</th>
                <th className="pb-2 pr-4">Attempts</th>
                <th className="pb-2">Created</th>
              </tr>
            </thead>
            <tbody>
              {jobs.map(j => (
                <tr key={j.id} className="border-b last:border-0 hover:bg-muted/50 cursor-pointer">
                  <td className="py-2 pr-4">
                    <Link
                      href={`/dashboard/fleet/jobs/${j.id}`}
                      className="hover:underline font-mono text-xs"
                      aria-label={`View job ${j.idempotencyKey}`}
                    >
                      {j.idempotencyKey}
                    </Link>
                  </td>
                  <td className="py-2 pr-4">
                    <span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-muted">
                      {j.stage}
                    </span>
                  </td>
                  <td className="py-2 pr-4 capitalize">{j.priority}</td>
                  <td className="py-2 pr-4">{j.kind}</td>
                  <td className="py-2 pr-4">{j.attempts}</td>
                  <td className="py-2 text-xs text-muted-foreground">
                    {new Date(j.createdAt).toLocaleString()}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
