"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useTenantId } from "@/hooks/useTenantId";
import { experienceApi } from "@/modules/experience/services/experience-api";
import { ExperiencePageLoader, ExperiencePageError, ExperienceEmptyState } from "@/modules/experience/pages/shared";
import { PageHeader, Card, CardContent, Input, FormField, Button } from "@/components/ds";
import { ExperienceBreadcrumbs } from "@/modules/experience/components/ExperienceBreadcrumbs";

export const AuditLogsPage = function ExperienceAuditPage() {
  const { tenantId } = useTenantId();
  const [entityType, setEntityType] = useState("");
  const [entityId, setEntityId] = useState("");
  const [submitted, setSubmitted] = useState<{ type?: string; id?: string } | null>(null);

  const q = useQuery({
    queryKey: ["experience", tenantId, "audit", submitted],
    queryFn: () =>
      experienceApi.audit.list(tenantId!, {
        entity_type: submitted?.type,
        entity_id: submitted?.id,
        limit: 50,
      }),
    enabled: !!tenantId,
  });

  return (
    <div className="space-y-6">
      <ExperienceBreadcrumbs current="ممیزی" />
      <PageHeader title="لاگ ممیزی" description="جستجو بر اساس entity_type و entity_id (اختیاری)." />
      <Card>
        <CardContent className="flex flex-wrap gap-4 p-4">
          <FormField label="نوع موجودیت"><Input value={entityType} onChange={(e) => setEntityType(e.target.value)} placeholder="page" /></FormField>
          <FormField label="شناسه"><Input value={entityId} onChange={(e) => setEntityId(e.target.value)} /></FormField>
          <Button onClick={() => setSubmitted({ type: entityType || undefined, id: entityId || undefined })}>جستجو</Button>
        </CardContent>
      </Card>
      {q.isLoading ? <ExperiencePageLoader /> : null}
      {q.error ? <ExperiencePageError error={q.error} onRetry={() => q.refetch()} /> : null}
      {!q.isLoading && !q.error && (q.data?.length ?? 0) === 0 ? <ExperienceEmptyState title="لاگی یافت نشد" /> : null}
      <div className="space-y-2">
        {(q.data ?? []).map((log) => (
          <Card key={String(log.id)}><CardContent className="p-3 text-sm">
            <strong>{String(log.action)}</strong> — {String(log.entity_type)} — {new Date(String(log.created_at)).toLocaleString("fa-IR")}
          </CardContent></Card>
        ))}
      </div>
    </div>
  );
};
export default AuditLogsPage;
