import { auth } from "@/auth";
import { db } from "@/lib/db";
import { redirect } from "next/navigation";
import { distanceKm } from "@/lib/geo";
import { hasPermission } from "@/lib/permissions";
import { VendorsTable } from "./vendors-table";
import { AddVendorButton } from "@/app/(portal)/admin/vendors/vendor-form";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "Vendors" };

interface Props {
  searchParams: Promise<{ siteId?: string }>;
}

export default async function InventoryVendorsPage({ searchParams }: Props) {
  const session = await auth();
  if (!session?.user) redirect("/login");

  const { siteId } = await searchParams;

  const [site, vendors, sites] = await Promise.all([
    siteId
      ? db.site.findUnique({
          where: { id: siteId, isActive: true },
          select: { id: true, name: true, latitude: true, longitude: true },
        })
      : Promise.resolve(null),
    db.vendor.findMany({
      where: { isActive: true },
      include: {
        contacts: {
          where: { isPrimary: true },
          take: 1,
        },
        _count: { select: { vendorPrices: true } },
      },
      orderBy: { name: "asc" },
    }),
    db.site.findMany({
      where: { isActive: true },
      orderBy: { name: "asc" },
      select: { id: true, name: true, code: true },
    }),
  ]);

  const rows = vendors.map((v) => {
    let dist: number | null = null;
    if (site?.latitude && site.longitude && v.latitude && v.longitude) {
      dist = distanceKm(site.latitude, site.longitude, v.latitude, v.longitude);
    }
    return {
      id: v.id,
      name: v.name,
      vendorId: v.vendorId ?? null,
      gstin: v.gstin ?? null,
      address: v.address ?? null,
      isVerified: v.isVerified,
      itemCount: v._count.vendorPrices,
      primaryContact: v.contacts[0]
        ? { name: v.contacts[0].name, mobile: v.contacts[0].mobile ?? null }
        : null,
      distanceKm: dist,
    };
  });

  // Submitters can add vendors here; without manage_vendors the vendor stays unverified.
  const canCreate = hasPermission(session.user.role, "create_vendor");
  const canVerify = hasPermission(session.user.role, "manage_vendors");

  return (
    <div className="max-w-6xl">
      <div className="mb-6 flex items-start justify-between gap-4">
        <div>
          <h1 className="text-2xl font-semibold text-neutral-900">Vendors</h1>
          <p className="mt-1 text-sm text-neutral-500">Browse vendors and their distance from your working site.</p>
        </div>
        {canCreate && <AddVendorButton simple={!canVerify} />}
      </div>
      <VendorsTable
        vendors={rows}
        hasSite={!!site}
        sites={sites}
        currentSiteId={siteId ?? null}
      />
    </div>
  );
}
