import { createClient } from "@/lib/supabase/server";
import { ReportTable } from "@/components/reports/report-table";
import type { ReportColumn } from "@/lib/types";

/** Normalize a Supabase embed (object | array | null) to the first row's `name`. */
function name(x: unknown): string {
  const row = Array.isArray(x) ? x[0] : x;
  if (row && typeof row === "object" && "name" in row) {
    const n = (row as { name?: unknown }).name;
    return n ? String(n) : "—";
  }
  return "—";
}

function date(d: unknown): string {
  return d ? new Date(d as string).toLocaleDateString() : "—";
}

export default async function Page() {
  const supabase = await createClient();

  const { data: leads } = await supabase
    .from("leads")
    .select(
      "id, full_name, phone, email, country, lead_status, created_at, source:lead_sources(name), branch:branches(name)",
    )
    .order("created_at", { ascending: false });

  const columns: ReportColumn[] = [
    { key: "date", label: "Date" },
    { key: "name", label: "Name" },
    { key: "phone", label: "Phone" },
    { key: "email", label: "Email" },
    { key: "country", label: "Country" },
    { key: "source", label: "Source" },
    { key: "status", label: "Status" },
    { key: "branch", label: "Branch" },
  ];

  const rows = (leads ?? []).map((l) => ({
    date: date(l.created_at),
    name: l.full_name ?? "—",
    phone: l.phone ?? "—",
    email: l.email ?? "—",
    country: l.country ?? "—",
    source: name(l.source),
    status: l.lead_status ?? "—",
    branch: name(l.branch),
  }));

  return (
    <ReportTable
      title="Lead Form Report"
      breadcrumb="Home / Reports / Lead Form"
      columns={columns}
      rows={rows}
    />
  );
}
