"use client";

import { useState, useMemo } from "react";
import type { QuarantinedAssertion } from "@/lib/api/types";
import { QuarantineRow } from "./quarantine-row";
import { QuarantineFilters } from "./quarantine-filters";
import { QuarantineEmptyState } from "./quarantine-empty-state";

interface QuarantineListProps {
  assertions: QuarantinedAssertion[];
  onRestore: (hash: string) => Promise<void>;
  onDelete: (hash: string) => Promise<void>;
}

export function QuarantineList({
  assertions,
  onRestore,
  onDelete,
}: QuarantineListProps) {
  const [selectedReason, setSelectedReason] = useState<string | null>(null);
  const [processingHash, setProcessingHash] = useState<string | null>(null);
  const [processingAction, setProcessingAction] = useState<"restore" | "delete" | null>(null);

  // Get unique reasons for filter dropdown
  const availableReasons = useMemo(() => {
    const reasons = new Set(assertions.map((a) => a.reason));
    return Array.from(reasons).sort();
  }, [assertions]);

  // Filter assertions by reason
  const filteredAssertions = useMemo(() => {
    if (!selectedReason) return assertions;
    return assertions.filter((a) => a.reason === selectedReason);
  }, [assertions, selectedReason]);

  const handleRestore = async (hash: string) => {
    setProcessingHash(hash);
    setProcessingAction("restore");
    try {
      await onRestore(hash);
    } finally {
      setProcessingHash(null);
      setProcessingAction(null);
    }
  };

  const handleDelete = async (hash: string) => {
    setProcessingHash(hash);
    setProcessingAction("delete");
    try {
      await onDelete(hash);
    } finally {
      setProcessingHash(null);
      setProcessingAction(null);
    }
  };

  if (assertions.length === 0) {
    return <QuarantineEmptyState hasFilter={false} />;
  }

  return (
    <div className="space-y-4">
      <QuarantineFilters
        selectedReason={selectedReason}
        onReasonChange={setSelectedReason}
        availableReasons={availableReasons}
      />

      {filteredAssertions.length === 0 ? (
        <QuarantineEmptyState
          hasFilter={true}
          onClearFilter={() => setSelectedReason(null)}
        />
      ) : (
        <div className="space-y-3">
          {filteredAssertions.map((item) => (
            <QuarantineRow
              key={item.hash}
              item={item}
              onRestore={handleRestore}
              onDelete={handleDelete}
              isRestoring={
                processingHash === item.hash && processingAction === "restore"
              }
              isDeleting={
                processingHash === item.hash && processingAction === "delete"
              }
            />
          ))}
        </div>
      )}

      {filteredAssertions.length > 0 && (
        <p className="text-xs text-muted-foreground text-center">
          Showing {filteredAssertions.length} of {assertions.length} quarantined items
        </p>
      )}
    </div>
  );
}
