'use client';

import React, { useEffect, useState } from 'react';
import { JobTypePill } from '@/components/admin/JobTypePill';
import styles from './page.module.css';

interface JobRow {
  id: string;
  type: string;
  dealerId: string;
  dealerName: string | null;
  domain: string | null;
  attempts: number;
  lastError: string | null;
  updatedAt: string;
}

interface Props {
  status: 'pending' | 'running' | 'completed' | 'failed' | 'dead_letter';
  limit?: number;
  sinceHours?: number;
  onSelectDealer?: (id: string) => void;
}

export function QueueHealthDrawer({ status, limit = 25, sinceHours, onSelectDealer }: Props) {
  const [jobs, setJobs] = useState<JobRow[] | null>(null);
  const [total, setTotal] = useState<number>(0);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    const params = new URLSearchParams({ status, limit: String(limit) });
    if (sinceHours && sinceHours > 0) params.set('sinceHours', String(sinceHours));
    fetch(`/api/admin/gsc/jobs?${params}`)
      .then((r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then((data) => {
        if (cancelled) return;
        setJobs(data.jobs);
        setTotal(data.total);
      })
      .catch((e) => !cancelled && setError(e.message));
    return () => {
      cancelled = true;
    };
  }, [status, limit, sinceHours]);

  if (error) {
    return (
      <div className={styles.errorBanner} role="alert">
        <p>Failed to load: {error}</p>
      </div>
    );
  }
  if (!jobs) return <p className={styles.loadingMsg}>Loading…</p>;
  if (total === 0) return <p className={styles.emptyState}>No jobs in this state.</p>;

  return (
    <div className={styles.tableWrapper}>
      <table className={styles.table}>
        <thead>
          <tr>
            <th>Dealer</th>
            <th>Domain</th>
            <th>Type</th>
            <th>Attempts</th>
            <th>Updated</th>
          </tr>
        </thead>
        <tbody>
          {jobs.map((j) => (
            <tr key={j.id}>
              <td
                className={onSelectDealer ? styles.clickableCell : undefined}
                onClick={onSelectDealer ? () => onSelectDealer(j.dealerId) : undefined}
              >
                {j.dealerName ?? j.dealerId}
              </td>
              <td>{j.domain ?? '—'}</td>
              <td>
                <JobTypePill type={j.type} />
              </td>
              <td>{j.attempts}</td>
              <td>{new Date(j.updatedAt).toLocaleString()}</td>
            </tr>
          ))}
        </tbody>
      </table>
      {total > jobs.length && (
        <p className={styles.emptyState}>
          Showing {jobs.length} of {total}.
        </p>
      )}
    </div>
  );
}
