import Link from "next/link";
import { executeGraphQL } from "@/lib/graphql/client";
import { PageHeader } from "@/components/layout/page-header";
import { Button } from "@/components/ui/button";
import { LeadsTable } from "./leads-table";
import { LEAD_STATUSES } from "@/lib/leads/constants";
import type { Lead } from "@/lib/types";

type LeadRow = Lead & { source?: { name: string } | null };

const PAGE_SIZE = 20;

const GET_LEADS_QUERY = `
  query GetLeads($first: Int, $offset: Int, $filter: leadsFilter, $orderBy: [leadsOrderBy!]) {
    leadsCollection(first: $first, offset: $offset, filter: $filter, orderBy: $orderBy) {
      edges {
        node {
          id
          full_name
          email
          phone
          country
          lead_status
          created_at
          lead_sources {
            name
          }
        }
      }
    }
  }
`;

export default async function AllLeadsPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; status?: string; country?: string; page?: string }>;
}) {
  const sp = await searchParams;
  const q = sp.q?.trim() ?? "";
  const status =
    sp.status && LEAD_STATUSES.includes(sp.status as never) ? sp.status : "";
  const country = sp.country?.trim() ?? "";
  const page = Math.max(1, Number(sp.page) || 1);
  const offset = (page - 1) * PAGE_SIZE;

  const filterConditions: any[] = [];
  if (status) {
    filterConditions.push({ lead_status: { eq: status } });
  }
  if (country) {
    filterConditions.push({ country: { ilike: `%${country}%` } });
  }
  if (q) {
    filterConditions.push({
      or: [
        { full_name: { ilike: `%${q}%` } },
        { phone: { ilike: `%${q}%` } },
        { email: { ilike: `%${q}%` } },
      ],
    });
  }

  const filter = filterConditions.length > 0 ? { and: filterConditions } : undefined;

  const { data, errors } = await executeGraphQL(GET_LEADS_QUERY, {
    first: PAGE_SIZE,
    offset,
    filter,
    orderBy: [{ created_at: "DescNullsLast" }],
  });

  if (errors) {
    console.error("GraphQL errors fetching leads:", errors);
  }

  const rawEdges = data?.leadsCollection?.edges ?? [];
  const leads: LeadRow[] = rawEdges.map((edge: any) => ({
    ...edge.node,
    source: edge.node.lead_sources ? { name: edge.node.lead_sources.name } : null,
  }));

  const total = leads.length < PAGE_SIZE && page === 1 ? leads.length : undefined;

  return (
    <div>
      <PageHeader
        title="All Leads"
        breadcrumb="Home / All Leads"
        action={
          <Button asChild>
            <Link href="/leads/new">Add Lead</Link>
          </Button>
        }
      />
      <LeadsTable
        leads={leads}
        total={total}
        page={page}
        pageSize={PAGE_SIZE}
        filters={{ q, status, country }}
      />
    </div>
  );
}

