import { prisma } from "@/lib/prisma";
import { addNonServiceablePincode, deleteNonServiceablePincode } from "@/lib/actions/shipping";
import ShippingTabs from "@/components/admin/ShippingTabs";

export default async function AdminPincodeServiceabilityPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const { error } = await searchParams;
  const pincodes = await prisma.nonServiceablePincode.findMany({ orderBy: { pincode: "asc" } });

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Pincode Serviceability</h1>
      <p className="mt-1 text-sm text-stone-500">
        By default every pincode is deliverable. Add one here to block checkout for a pincode you genuinely can&apos;t
        ship to — there&apos;s no courier API behind this, so it only enforces what you list, not real-time coverage.
      </p>

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

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

      <form action={addNonServiceablePincode} className="flex max-w-lg gap-2">
        <input name="pincode" required placeholder="Pincode" className="w-32 rounded-md border border-stone-300 px-3 py-2 text-sm" />
        <input name="reason" placeholder="Reason (optional)" className="flex-1 rounded-md border border-stone-300 px-3 py-2 text-sm" />
        <button type="submit" className="rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800">
          Block
        </button>
      </form>

      <div className="mt-6 overflow-hidden rounded-lg border border-rose-100 bg-white">
        {pincodes.length === 0 ? (
          <p className="p-4 text-sm text-stone-500">No blocked pincodes — everywhere is currently deliverable.</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">Pincode</th>
                <th className="p-3">Reason</th>
                <th className="p-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {pincodes.map((p) => (
                <tr key={p.id}>
                  <td className="p-3 font-medium text-stone-800">{p.pincode}</td>
                  <td className="p-3 text-stone-600">{p.reason ?? "—"}</td>
                  <td className="p-3 text-right">
                    <form action={deleteNonServiceablePincode.bind(null, p.id)}>
                      <button type="submit" className="text-xs text-stone-400 hover:text-red-700">
                        Unblock
                      </button>
                    </form>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
