"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Input, PageHeader, EmptyState } from "@/components/ds";
import { loyaltyApi } from "@/modules/loyalty/services/loyalty-api";
import { useTenantId } from "@/hooks/useTenantId";
import { LoyaltyBreadcrumbs } from "@/modules/loyalty/components/LoyaltyBreadcrumbs";
import { LoyaltyPageLoader, LoyaltyPageError } from "@/modules/loyalty/pages/shared";
import { LoyaltyTablePage } from "@/modules/loyalty/design-system";

export default function AuditLogsPage() {
  const { tenantId } = useTenantId();
  const [entityType, setEntityType] = useState("member");
  const [entityId, setEntityId] = useState("");
  const q = useQuery({
    queryKey: ["loyalty", tenantId, "audit", entityType, entityId],
    queryFn: () => loyaltyApi.audit.list(tenantId!, entityType, entityId),
    enabled: !!tenantId && !!entityId,
  });

  if (!tenantId) return <LoyaltyPageLoader />;

  return (
    <div>
      <LoyaltyBreadcrumbs items={[{ label: "لاگ ممیزی" }]} />
      <PageHeader
        title="ممیزی"
        description="GET /audit?entity_type&entity_id — لاگ per-entity."
      />
      <div className="mb-4 flex flex-wrap gap-3">
        <Input
          placeholder="entity_type"
          value={entityType}
          onChange={(e) => setEntityType(e.target.value)}
        />
        <Input
          placeholder="entity UUID"
          value={entityId}
          onChange={(e) => setEntityId(e.target.value)}
          className="max-w-md"
        />
      </div>
      {entityId && q.isLoading ? <LoyaltyPageLoader /> : null}
      {q.error ? <LoyaltyPageError error={q.error} onRetry={() => q.refetch()} /> : null}
      {entityId && q.data ? (
        <LoyaltyTablePage
          title="رویدادها"
          columns={[
            { key: "action", header: "عمل" },
            { key: "actor_user_id", header: "کاربر" },
            { key: "message", header: "پیام" },
            { key: "created_at", header: "زمان" },
          ]}
          rows={q.data as unknown as Record<string, unknown>[]}
        />
      ) : (
        !entityId && <EmptyState title="UUID موجودیت را وارد کنید" />
      )}
    </div>
  );
}
