import { prisma } from "@/lib/prisma";
import { createCourierPartner, toggleCourierPartner, deleteCourierPartner } from "@/lib/actions/shipping";
import ShippingTabs from "@/components/admin/ShippingTabs";

export default async function AdminCourierPartnersPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const { error } = await searchParams;
  const partners = await prisma.courierPartner.findMany({
    orderBy: { name: "asc" },
    include: { _count: { select: { orders: true } } },
  });

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Courier Partners</h1>
      <p className="mt-1 text-sm text-stone-500">The couriers you actually ship with — pick one when marking an order shipped.</p>

      <ShippingTabs active="/iv-manage-84x2/shipping/couriers" />

      {error && <p className="mb-4 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      <form action={createCourierPartner} className="grid max-w-2xl grid-cols-1 gap-3 rounded-lg border border-rose-100 bg-white p-4 sm:grid-cols-4">
        <input name="name" required placeholder="Courier name" className="rounded-md border border-stone-300 px-2 py-2 text-sm sm:col-span-2" />
        <input
          name="phone"
          type="tel"
          inputMode="numeric"
          pattern="\d{10}"
          maxLength={10}
          title="Enter a 10-digit mobile number"
          placeholder="Phone (optional)"
          className="rounded-md border border-stone-300 px-2 py-2 text-sm"
        />
        <input name="notes" placeholder="Notes (optional)" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
        <button type="submit" className="col-span-1 rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800 sm:col-span-4">
          Add courier
        </button>
      </form>

      <div className="mt-8 overflow-hidden rounded-lg border border-rose-100 bg-white">
        {partners.length === 0 ? (
          <p className="p-4 text-sm text-stone-500">No couriers added yet.</p>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-rose-50/60 text-left text-xs uppercase text-stone-500">
              <tr>
                <th className="p-3">Name</th>
                <th className="p-3">Phone</th>
                <th className="p-3">Notes</th>
                <th className="p-3">Shipments</th>
                <th className="p-3">Status</th>
                <th className="p-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {partners.map((p) => (
                <tr key={p.id}>
                  <td className="p-3 font-medium text-stone-800">{p.name}</td>
                  <td className="p-3 text-stone-600">{p.phone ?? "—"}</td>
                  <td className="p-3 text-stone-600">{p.notes ?? "—"}</td>
                  <td className="p-3 text-stone-600">{p._count.orders}</td>
                  <td className="p-3">
                    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${p.active ? "bg-emerald-100 text-emerald-800" : "bg-stone-200 text-stone-600"}`}>
                      {p.active ? "Active" : "Inactive"}
                    </span>
                  </td>
                  <td className="p-3 text-right">
                    <div className="flex items-center justify-end gap-3">
                      <form action={toggleCourierPartner.bind(null, p.id)}>
                        <button type="submit" className="text-xs text-stone-500 hover:text-rose-700">
                          {p.active ? "Deactivate" : "Activate"}
                        </button>
                      </form>
                      <form action={deleteCourierPartner.bind(null, p.id)}>
                        <button type="submit" className="text-xs text-stone-400 hover:text-red-700">
                          Delete
                        </button>
                      </form>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
