"use client";

import { useState, useMemo } from "react";
import type { AuditEntry } from "@/lib/api/types";
import { AuditRow } from "./audit-row";
import { AuditFilters, type AuditFilterValues } from "./audit-filters";
import { AuditEmptyState } from "./audit-empty-state";
import { AuditExport } from "./audit-export";
import { Button } from "@/components/ui/button";

interface AuditListProps {
  entries: AuditEntry[];
  totalCount: number;
  filters: AuditFilterValues;
  onFilterChange: (filters: AuditFilterValues) => void;
}

const ITEMS_PER_PAGE = 20;

export function AuditList({ entries, totalCount, filters, onFilterChange }: AuditListProps) {
  const [page, setPage] = useState(0);

  // Get unique lenses for filter dropdown (client-side for dropdown options)
  const availableActions = useMemo(() => {
    const lenses = new Set(entries.map((e) => e.params.lens).filter(Boolean) as string[]);
    return Array.from(lenses).sort();
  }, [entries]);

  // Paginate (server already filtered)
  const paginatedEntries = useMemo(() => {
    const start = page * ITEMS_PER_PAGE;
    return entries.slice(start, start + ITEMS_PER_PAGE);
  }, [entries, page]);

  const totalPages = Math.ceil(entries.length / ITEMS_PER_PAGE);
  const hasFilters =
    filters.subject !== "" ||
    filters.predicate !== "" ||
    filters.agentId !== "" ||
    filters.action !== "" ||
    filters.timeRange !== "24h";

  const handleClearFilters = () => {
    onFilterChange({ subject: "", predicate: "", agentId: "", action: "", timeRange: "24h" });
    setPage(0);
  };

  const handleFilterChange = (newFilters: AuditFilterValues) => {
    onFilterChange(newFilters);
    setPage(0); // Reset to first page when filters change
  };

  if (entries.length === 0 && !hasFilters) {
    return <AuditEmptyState hasFilters={false} />;
  }

  return (
    <div className="space-y-4">
      {/* Filters and Export */}
      <div className="flex items-center justify-between flex-wrap gap-4">
        <AuditFilters
          values={filters}
          onChange={handleFilterChange}
          availableActions={availableActions}
        />
        <AuditExport entries={entries} />
      </div>

      {/* Table header - hidden on mobile */}
      <div className="hidden sm:grid grid-cols-6 gap-4 px-4 py-2 text-xs font-medium text-muted-foreground uppercase tracking-wide border-b border-border">
        <div>Time</div>
        <div>Agent</div>
        <div>Lens</div>
        <div>Target</div>
        <div>Confidence</div>
        <div>Result</div>
      </div>

      {/* Entries */}
      {entries.length === 0 ? (
        <AuditEmptyState hasFilters={hasFilters} onClearFilters={handleClearFilters} />
      ) : (
        <div className="space-y-2">
          {paginatedEntries.map((entry) => (
            <AuditRow key={entry.query_id} entry={entry} />
          ))}
        </div>
      )}

      {/* Pagination */}
      {entries.length > 0 && totalPages > 1 && (
        <div className="flex items-center justify-center gap-2 pt-4">
          <Button
            variant="outline"
            size="sm"
            onClick={() => setPage((p) => Math.max(0, p - 1))}
            disabled={page === 0}
          >
            Previous
          </Button>
          <span className="text-sm text-muted-foreground">
            Page {page + 1} of {totalPages}
          </span>
          <Button
            variant="outline"
            size="sm"
            onClick={() => setPage((p) => Math.min(totalPages - 1, p + 1))}
            disabled={page >= totalPages - 1}
          >
            Next
          </Button>
        </div>
      )}

      {/* Summary */}
      <p className="text-xs text-muted-foreground text-center pt-2">
        Showing {paginatedEntries.length} of {entries.length} entries
        {entries.length < totalCount && ` (${totalCount} total)`}
      </p>
    </div>
  );
}
