"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useTenantId } from "@/hooks/useTenantId";
import { deliveryApi } from "@/modules/delivery/services/delivery-api";
import { DeliveryPageLoader, DeliveryPageError, DeliveryEmptyState } from "@/modules/delivery/pages/shared";
import { PageHeader, Card, CardContent, Input, FormField, Button } from "@/components/ds";
import { DeliveryBreadcrumbs } from "@/modules/delivery/components/DeliveryBreadcrumbs";

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

  const q = useQuery({
    queryKey: ["delivery", tenantId, "audit", submitted],
    queryFn: () => deliveryApi.audit.list(tenantId!, {
      entity_type: submitted!.type,
      entity_id: submitted!.id,
    }),
    enabled: !!tenantId && !!submitted,
  });

  return (
    <div className="space-y-6">
      <DeliveryBreadcrumbs 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)} /></FormField>
          <FormField label="شناسه"><Input value={entityId} onChange={(e) => setEntityId(e.target.value)} /></FormField>
          <Button onClick={() => setSubmitted({ type: entityType, id: entityId })}>جستجو</Button>
        </CardContent>
      </Card>
      {submitted && q.isLoading ? <DeliveryPageLoader /> : null}
      {q.error ? <DeliveryPageError error={q.error} onRetry={() => q.refetch()} /> : null}
      {submitted && !q.isLoading && !q.error && (q.data?.length ?? 0) === 0 ? (
        <DeliveryEmptyState 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> — {new Date(String(log.created_at)).toLocaleString("fa-IR")}
            {log.message ? <p className="text-[var(--muted)]">{String(log.message)}</p> : null}
          </CardContent></Card>
        ))}
      </div>
    </div>
  );
};
export default AuditLogsPage;
