import { Bot, History } from 'lucide-react';

import { useMemo } from 'react';

import { Head } from '@inertiajs/react';
import { router } from '@inertiajs/react';

import EditorialPageHeader from '@/Components/layout/EditorialPageHeader';
import { DataTable } from '@/Components/ui/data-table';
import { EmptyState } from '@/Components/ui/empty-state';
import DashboardLayout from '@/Layouts/DashboardLayout';
import type { PaginatedResponse, SiteBasic } from '@/types';
import type { AutopilotRunRow } from '@/types/recovery-runs';

import { recoveryRunsColumns } from './Index.columns';

interface Props {
  site: SiteBasic;
  runs: PaginatedResponse<AutopilotRunRow>;
}

/**
 * R7PROD-003 / R8UX-011 — Autopilot History.
 *
 * Lists all AutopilotRun rows (autonomous system cycles) for a site in
 * newest-first order with server-side pagination. Distinct from the manual
 * Recovery Run journey (batch-ai.index) — this page is exclusively for
 * autopilot / autonomous runs.
 *
 * Canonical label: "Autopilot History" (RUN_NOUNS.autopilotPage).
 * Manual run history: "Recovery Runs" (batch-ai.index, RUN_NOUNS.manualRunPage).
 *
 * Route: GET /sites/{site}/recovery-runs
 * Name: sites.recovery-runs.index
 * Middleware: auth, can:view,site
 */
export default function RecoveryRunsIndex({ site, runs }: Props) {
  // R9UXB-101: pass site.id so the 'Review settings' action routes to the correct
  // site's schedule editor (sites.schedule.edit is bound by {site} integer id).
  const columns = useMemo(() => recoveryRunsColumns(site.id), [site.id]);

  const hasRuns = runs.total > 0;

  return (
    <>
      <Head title={`Autopilot History — ${site.name}`} />

      <EditorialPageHeader
        title="Autopilot History"
        subtitle={`Recovery run log for ${site.name} — every autonomous cycle, what it did, and what it cost`}
        readouts={
          hasRuns
            ? [
                {
                  label: 'Total runs',
                  value: (
                    <span className="tabular-nums">{runs.total}</span>
                  ),
                },
              ]
            : undefined
        }
      />

      <div className="container py-6">
        {!hasRuns ? (
          <EmptyState
            icon={Bot}
            title="No autopilot runs yet"
            description="When autopilot mode is enabled and a recovery run completes, each run will appear here with its targeted pages, published count, and cost."
            primaryAction={{
              label: 'Enable Autopilot',
              // D4-C-002: sites.schedule.edit is bound by integer {site} id (not public_id).
              href: route('sites.schedule.edit', { site: site.id }),
            }}
          />
        ) : (
          // R8FE-005: controlled pageIndex replaces key= remount hack.
          <DataTable
            columns={columns}
            data={runs.data}
            caption="Autopilot recovery run history"
            emptyState={{
              title: 'No runs on this page',
              description: 'Navigate to a different page to see more runs.',
              icon: History,
            }}
            manualPagination
            pageCount={runs.last_page}
            pageSize={runs.per_page}
            pageIndex={runs.current_page - 1}
            onPaginationChange={(pagination) => {
              router.get(
                route('sites.recovery-runs.index', site.id),
                { page: pagination.pageIndex + 1 },
                { preserveState: true, preserveScroll: true },
              );
            }}
          />
        )}
      </div>
    </>
  );
}

RecoveryRunsIndex.layout = (page: React.ReactNode) => (
  <DashboardLayout>{page}</DashboardLayout>
);
