"use client";

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

export default function ExportPage() {
  const { tenantId } = useTenantId();
  const q = useQuery({
    queryKey: ["crm", tenantId, "export-bundle"],
    queryFn: async () => {
      const [leads, contacts, orgs, opps] = await Promise.all([
        crmApi.leads.list(tenantId!, { page: 1, page_size: 500 }),
        crmApi.contacts.list(tenantId!, { page: 1, page_size: 500 }),
        crmApi.organizations.list(tenantId!, { page: 1, page_size: 500 }),
        crmApi.opportunities.list(tenantId!, { page: 1, page_size: 500 }),
      ]);
      return { leads, contacts, orgs, opps };
    },
    enabled: !!tenantId,
  });

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

  const d = q.data!;

  return (
    <div>
      <CrmBreadcrumbs items={[{ label: "خروجی" }]} />
      <PageHeader
        title="خروجی داده"
        description="Export client-side CSV از داده‌های fetch شده — بدون export API سرور."
      />
      <div className="flex flex-wrap gap-3">
        <Button
          variant="outline"
          onClick={() =>
            exportToCsv("leads.csv", d.leads as unknown as Record<string, unknown>[], [
              "lead_number",
              "full_name",
              "email",
              "status",
            ])
          }
        >
          سرنخ‌ها CSV
        </Button>
        <Button
          variant="outline"
          onClick={() =>
            exportToCsv("contacts.csv", d.contacts as unknown as Record<string, unknown>[], [
              "full_name",
              "email",
              "phone",
            ])
          }
        >
          مخاطبین CSV
        </Button>
        <Button
          variant="outline"
          onClick={() =>
            exportToCsv("organizations.csv", d.orgs as unknown as Record<string, unknown>[], [
              "name",
              "organization_number",
              "status",
            ])
          }
        >
          شرکت‌ها CSV
        </Button>
        <Button
          variant="outline"
          onClick={() =>
            exportToCsv("deals.csv", d.opps as unknown as Record<string, unknown>[], [
              "opportunity_number",
              "title",
              "amount",
              "status",
            ])
          }
        >
          معاملات CSV
        </Button>
      </div>
    </div>
  );
}
