"use client";

import { useCallback } from "react";
import type { AuditEntry } from "@/lib/api/types";
import { Button } from "@/components/ui/button";

interface AuditExportProps {
  entries: AuditEntry[];
  disabled?: boolean;
}

export function AuditExport({ entries, disabled }: AuditExportProps) {
  const exportJSON = useCallback(() => {
    const data = JSON.stringify(entries, null, 2);
    const blob = new Blob([data], { type: "application/json" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `audit-trail-${new Date().toISOString().split("T")[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }, [entries]);

  const exportCSV = useCallback(() => {
    // CSV header
    const headers = [
      "query_id",
      "timestamp",
      "agent_id",
      "subject",
      "predicate",
      "lens",
      "result_hash",
      "result_confidence",
      "contributing_count",
    ];

    // CSV rows
    const rows = entries.map((entry) => [
      entry.query_id,
      new Date(entry.timestamp).toISOString(),
      entry.agent_id ?? "",
      entry.params.subject ?? "",
      entry.params.predicate ?? "",
      entry.params.lens ?? "",
      entry.result_hash ?? "",
      entry.result_confidence.toString(),
      entry.contributing_assertions.length.toString(),
    ]);

    // Escape CSV values
    const escapeCSV = (value: string): string => {
      if (value.includes(",") || value.includes('"') || value.includes("\n")) {
        return `"${value.replace(/"/g, '""')}"`;
      }
      return value;
    };

    const csv = [
      headers.join(","),
      ...rows.map((row) => row.map(escapeCSV).join(",")),
    ].join("\n");

    const blob = new Blob([csv], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `audit-trail-${new Date().toISOString().split("T")[0]}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  }, [entries]);

  return (
    <div className="flex items-center gap-2">
      <Button
        variant="outline"
        size="sm"
        onClick={exportJSON}
        disabled={disabled || entries.length === 0}
      >
        Export JSON
      </Button>
      <Button
        variant="outline"
        size="sm"
        onClick={exportCSV}
        disabled={disabled || entries.length === 0}
      >
        Export CSV
      </Button>
    </div>
  );
}
