import { auth } from "@/auth";
import { db } from "@/lib/db";
import { notFound, redirect } from "next/navigation";
import Link from "next/link";
import { formatCurrency, formatDate } from "@/lib/utils";
import { VendorItemsTable } from "./vendor-items-table";
import type { Metadata } from "next";

interface Props { params: Promise<{ id: string }> }

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { id } = await params;
  const vendor = await db.vendor.findUnique({ where: { id }, select: { name: true } });
  return { title: vendor?.name ?? "Vendor Detail" };
}

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

  const { id } = await params;

  const vendor = await db.vendor.findUnique({
    where: { id, isActive: true },
    include: {
      contacts: { orderBy: [{ isPrimary: "desc" }, { createdAt: "asc" }] },
      vendorPrices: {
        include: { product: { select: { id: true, code: true, name: true, description: true, isActive: true } } },
        orderBy: { updatedAt: "desc" },
      },
    },
  });

  if (!vendor) notFound();

  const items = vendor.vendorPrices.map((vp) => ({
    id: vp.id,
    productId: vp.product.id,
    code: vp.product.code,
    name: vp.product.name,
    description: vp.product.description ?? "",
    isActive: vp.product.isActive,
    price: Number(vp.price),
    updatedAt: vp.updatedAt.toISOString(),
  }));

  return (
    <div className="max-w-5xl space-y-6">
      {/* Breadcrumb */}
      <div className="flex items-center gap-2 text-sm text-neutral-500">
        <Link href="/inventory/vendors" className="hover:text-neutral-700">Vendors</Link>
        <span>/</span>
        <span className="text-neutral-900 font-medium">{vendor.name}</span>
      </div>

      {/* Header */}
      <div>
        <div className="flex items-center gap-3 mb-1">
          {vendor.vendorId && <span className="font-mono text-xs text-neutral-500">{vendor.vendorId}</span>}
          <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${vendor.isVerified ? "bg-success-100 text-success-700" : "bg-warning-100 text-warning-700"}`}>
            {vendor.isVerified ? "Verified" : "Unverified"}
          </span>
        </div>
        <h1 className="text-2xl font-semibold text-neutral-900">{vendor.name}</h1>
      </div>

      {/* Details + Contacts */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        <div className="rounded-lg border border-neutral-200 bg-white p-6">
          <h2 className="text-sm font-semibold text-neutral-900 mb-4">Vendor Details</h2>
          <dl className="space-y-3 text-sm">
            {vendor.gstin && (
              <div>
                <dt className="text-neutral-500 text-xs uppercase tracking-wide font-medium mb-0.5">GSTIN</dt>
                <dd className="font-mono text-neutral-900 tracking-wide">{vendor.gstin}</dd>
              </div>
            )}
            {vendor.address && (
              <div>
                <dt className="text-neutral-500 text-xs uppercase tracking-wide font-medium mb-0.5">Address</dt>
                <dd className="text-neutral-900 whitespace-pre-wrap">{vendor.address}</dd>
              </div>
            )}
            {vendor.pincode && (
              <div>
                <dt className="text-neutral-500 text-xs uppercase tracking-wide font-medium mb-0.5">Pincode</dt>
                <dd className="font-mono text-neutral-900">{vendor.pincode}</dd>
              </div>
            )}
            {!vendor.gstin && !vendor.address && !vendor.pincode && (
              <p className="text-neutral-400 italic">No additional details on record.</p>
            )}
          </dl>
        </div>

        <div className="rounded-lg border border-neutral-200 bg-white p-6">
          <h2 className="text-sm font-semibold text-neutral-900 mb-4">
            Contacts
            <span className="ml-2 text-neutral-400 font-normal">({vendor.contacts.length})</span>
          </h2>
          {vendor.contacts.length === 0 ? (
            <p className="text-sm text-neutral-400 italic">No contacts on record.</p>
          ) : (
            <div className="space-y-3">
              {vendor.contacts.map((c) => (
                <div key={c.id} className="flex items-start gap-3">
                  <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary-100 text-xs font-semibold text-primary-700">
                    {c.name.slice(0, 2).toUpperCase()}
                  </div>
                  <div className="min-w-0">
                    <div className="flex items-center gap-2">
                      <span className="font-medium text-sm text-neutral-900">{c.name}</span>
                      {c.role && <span className="rounded bg-neutral-100 px-1.5 py-0.5 text-xs text-neutral-500">{c.role}</span>}
                      {c.isPrimary && <span className="rounded bg-primary-100 px-1.5 py-0.5 text-xs text-primary-700 font-medium">Primary</span>}
                    </div>
                    <div className="flex flex-wrap gap-x-3 gap-y-0.5 mt-0.5 text-xs text-neutral-500">
                      {c.mobile && <span>{c.mobile}</span>}
                      {c.email && <a href={`mailto:${c.email}`} className="hover:text-primary-600 hover:underline">{c.email}</a>}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Items supplied */}
      <VendorItemsTable items={items} />
    </div>
  );
}
