"use client";

import { useQuery } from "@tanstack/react-query";
import { PageHeader, EmptyState } from "@/components/ds";
import { crmApi } from "@/modules/crm/services/crm-api";
import { useTenantId } from "@/hooks/useTenantId";
import { CrmTablePage } from "@/modules/crm/design-system";
import { CrmBreadcrumbs } from "@/modules/crm/components/CrmBreadcrumbs";
import { CrmPageLoader, CrmPageError } from "@/modules/crm/pages/shared";

export default function TimelinePage() {
  const { tenantId } = useTenantId();
  const q = useQuery({
    queryKey: ["crm", tenantId, "timeline"],
    queryFn: () => crmApi.timeline.list(tenantId!, { page: 1, page_size: 500 }),
    enabled: !!tenantId,
  });

  if (!tenantId || q.isLoading) return <CrmPageLoader />;
  if (q.error) return <CrmPageError error={q.error} onRetry={() => q.refetch()} />;

  return (
    <CrmTablePage
      breadcrumbs={<CrmBreadcrumbs items={[{ label: "خط زمانی" }]} />}
      title="خط زمانی فروش"
      description="رویدادهای immutable timeline — فقط خواندنی از API."
      columns={[
        { key: "event_type", header: "نوع" },
        { key: "title", header: "عنوان" },
        { key: "summary", header: "خلاصه" },
        { key: "occurred_at", header: "زمان" },
      ]}
      rows={(q.data ?? []) as unknown as Record<string, unknown>[]}
      empty={<EmptyState title="رویدادی ثبت نشده" />}
    />
  );
}
