import { useState, useCallback, useEffect } from "react";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import { AuditLogItem } from "@/shared/components/audit-log/AuditLogDisplay";

type AuditLogsResponse = {
  count: number;
  items: AuditLogItem[];
};

type UseAuditLogsOptions = {
  resourceId?: string;
  entityName?: string;
  userId?: string;
  autoFetch?: boolean;
};

/**
 * Hook to fetch and manage audit logs
 * Supports fetching logs by various filters
 */
export const useAuditLogs = (
  endpoint: string,
  options: UseAuditLogsOptions = {},
) => {
  const { autoFetch = true, resourceId, entityName, userId } = options;
  const { t } = useTranslation();

  const [logs, setLogs] = useState<AuditLogItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [total, setTotal] = useState(0);

  const fetchLogs = useCallback(async () => {
    setLoading(true);
    setError(null);

    try {
      const url = new URL(endpoint, window.location.origin);

      if (resourceId) url.searchParams.append("resourceId", resourceId);
      if (entityName) url.searchParams.append("entityName", entityName);
      if (userId) url.searchParams.append("userId", userId);

      const response = await fetch(url.toString(), {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }

      const data: AuditLogsResponse = await response.json();
      setLogs(data.items || []);
      setTotal(data.count || 0);
    } catch (err: any) {
      const errorMessage = err.message || t("auditLog.fetchError", "Failed to fetch audit logs");
      setError(errorMessage);
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  }, [endpoint, resourceId, entityName, userId, t]);

  useEffect(() => {
    if (autoFetch) {
      fetchLogs();
    }
  }, [fetchLogs, autoFetch]);

  return {
    logs,
    loading,
    error,
    total,
    refetch: fetchLogs,
  };
};
