import { getAllLeads } from "@/lib/lead-service";
import { getOfferListCards } from "@/lib/offer-queries";
import { db } from "@/db";
import { clients } from "@/db/schema";
import { asc } from "drizzle-orm";
import { generateProposalDraft } from "../actions";
import { GeneraProposalForm } from "./GeneraProposalForm";

export const revalidate = 0;

export default async function GeneraPage({
  searchParams,
}: {
  searchParams: Promise<{ lead_id?: string }>;
}) {
  const { lead_id: preselectedLeadId } = await searchParams;

  const [leads, offerCards, allClients] = await Promise.all([
    getAllLeads(200),
    getOfferListCards(),
    db.select({ id: clients.id, name: clients.name, brand_name: clients.brand_name })
      .from(clients)
      .orderBy(asc(clients.name)),
  ]);

  const activeOffers = offerCards.filter((o) => !o.is_archived);

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      <div>
        <h1 className="text-2xl font-semibold text-foreground">Genera preventivo</h1>
        <p className="text-sm text-muted-foreground mt-1">
          Scegli il lead o il cliente e l&apos;offerta. L&apos;AI legge i transcript e genera la bozza.
        </p>
      </div>
      <GeneraProposalForm
        leads={leads.map((l) => ({ id: l.id, name: l.name, company: l.company }))}
        clients={allClients}
        offers={activeOffers}
        action={generateProposalDraft}
        preselectedLeadId={preselectedLeadId}
      />
    </div>
  );
}
