import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { notFound, redirect } from "next/navigation";
import Link from "next/link";
import { formatCurrency, formatDate } from "@/lib/utils";
import { EditVendorButton } from "../vendor-form";
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" };
}

const STATUS_LABELS: Record<string, string> = {
  DRAFT: "Draft", SUBMITTED: "Submitted", MGR_REVIEW: "Under Review",
  MGR_APPROVED: "Approved", SENT_FOR_PAYMENT: "Sent for Payment",
  PAID_DELIVERED: "Paid", CLOSED: "Closed", REJECTED: "Rejected", CANCELLED: "Cancelled",
  EDITS_REQUESTED: "Edits Requested", VENDOR_ID_PENDING: "Vendor ID Pending",
};

export default async function VendorDetailPage({ params }: Props) {
  const session = await auth();
  if (!session?.user) redirect("/login");
  if (!hasPermission(session.user.role, "manage_vendors")) redirect("/dashboard");

  const { id } = await params;

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

  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="/admin/vendors" className="hover:text-neutral-700">Vendors</Link>
        <span>/</span>
        <span className="text-neutral-900 font-medium">{vendor.name}</span>
      </div>

      {/* Header */}
      <div className="flex items-start justify-between gap-4">
        <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>
            <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${vendor.isActive ? "bg-success-100 text-success-700" : "bg-neutral-100 text-neutral-500"}`}>
              {vendor.isActive ? "Active" : "Inactive"}
            </span>
          </div>
          <h1 className="text-2xl font-semibold text-neutral-900">{vendor.name}</h1>
        </div>
        <EditVendorButton vendor={{
          id: vendor.id,
          name: vendor.name,
          vendorId: vendor.vendorId,
          address: vendor.address ?? null,
          pincode: vendor.pincode ?? null,
          gstin: vendor.gstin ?? null,
          isActive: vendor.isActive,
          contacts: vendor.contacts.map((c) => ({
            name: c.name, role: c.role ?? "", mobile: c.mobile ?? "",
            email: c.email ?? "", isPrimary: c.isPrimary,
          })),
        }} />
      </div>

      {/* Vendor Info + Contacts */}
      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        {/* Details */}
        <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>
            )}
          </dl>
        </div>

        {/* Contacts */}
        <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 — searchable client component */}
      <VendorItemsTable items={items} />

      {/* Recent POs */}
      {vendor.purchaseOrders.length > 0 && (
        <div className="rounded-lg border border-neutral-200 bg-white p-6">
          <h2 className="text-sm font-semibold text-neutral-900 mb-4">Recent Purchase Orders</h2>
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-neutral-200">
                <th className="pb-2 text-left font-medium text-neutral-600">PO Number</th>
                <th className="pb-2 text-left font-medium text-neutral-600 pl-4">Status</th>
                <th className="pb-2 text-right font-medium text-neutral-600 pl-4">Amount</th>
                <th className="pb-2 text-right font-medium text-neutral-600 pl-4">Date</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-neutral-100">
              {vendor.purchaseOrders.map((po) => (
                <tr key={po.id} className="hover:bg-neutral-50">
                  <td className="py-2.5 pr-4">
                    <Link href={`/po/${po.id}`} className="font-mono text-xs text-primary-600 hover:underline">
                      {po.poNumber}
                    </Link>
                  </td>
                  <td className="py-2.5 pl-4 text-neutral-600">{STATUS_LABELS[po.status] ?? po.status}</td>
                  <td className="py-2.5 pl-4 text-right text-neutral-900">{formatCurrency(Number(po.totalAmount))}</td>
                  <td className="py-2.5 pl-4 text-right text-neutral-500">{formatDate(po.createdAt)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
