import { prisma } from "@/lib/prisma";
import { formatPaise } from "@/lib/format";
import { createShippingMethod, setDefaultShippingMethod, toggleShippingMethod, deleteShippingMethod } from "@/lib/actions/shipping";
import ShippingTabs from "@/components/admin/ShippingTabs";

export default async function AdminShippingMethodsPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const { error } = await searchParams;
  const methods = await prisma.shippingMethod.findMany({ orderBy: { createdAt: "asc" } });

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Shipping Methods</h1>
      <p className="mt-1 text-sm text-stone-500">
        The delivery options customers can be offered (e.g. Standard, Express). The default method&apos;s rate is what checkout actually charges today — there&apos;s no method picker on the storefront yet, so this is ready for when you add one.
      </p>

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

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

      <form action={createShippingMethod} className="grid max-w-2xl grid-cols-2 gap-3 rounded-lg border border-rose-100 bg-white p-4 sm:grid-cols-4">
        <input name="name" required placeholder="Name (e.g. Standard)" className="rounded-md border border-stone-300 px-2 py-2 text-sm sm:col-span-2" />
        <input name="ratePerKg" type="number" min={0} step="0.01" placeholder="₹/kg" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
        <input name="estimatedDays" placeholder="e.g. 3-5 days" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
        <button type="submit" className="col-span-2 rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800 sm:col-span-4">
          Add method
        </button>
      </form>

      <div className="mt-8 overflow-hidden rounded-lg border border-rose-100 bg-white">
        {methods.length === 0 ? (
          <p className="p-4 text-sm text-stone-500">No shipping methods yet — add one to enable checkout shipping.</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">Rate</th>
                <th className="p-3">Est. delivery</th>
                <th className="p-3">Default</th>
                <th className="p-3">Status</th>
                <th className="p-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {methods.map((m) => (
                <tr key={m.id}>
                  <td className="p-3 font-medium text-stone-800">{m.name}</td>
                  <td className="p-3 text-stone-600">{formatPaise(m.ratePerKgPaise)}/kg</td>
                  <td className="p-3 text-stone-600">{m.estimatedDays ?? "—"}</td>
                  <td className="p-3">
                    {m.isDefault ? (
                      <span className="rounded-full bg-rose-100 px-2 py-0.5 text-xs font-medium text-rose-800">Default</span>
                    ) : (
                      <form action={setDefaultShippingMethod.bind(null, m.id)}>
                        <button type="submit" className="text-xs text-stone-500 hover:text-rose-700">
                          Make default
                        </button>
                      </form>
                    )}
                  </td>
                  <td className="p-3">
                    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${m.active ? "bg-emerald-100 text-emerald-800" : "bg-stone-200 text-stone-600"}`}>
                      {m.active ? "Active" : "Inactive"}
                    </span>
                  </td>
                  <td className="p-3 text-right">
                    <div className="flex items-center justify-end gap-3">
                      {!m.isDefault && (
                        <form action={toggleShippingMethod.bind(null, m.id)}>
                          <button type="submit" className="text-xs text-stone-500 hover:text-rose-700">
                            {m.active ? "Deactivate" : "Activate"}
                          </button>
                        </form>
                      )}
                      {!m.isDefault && (
                        <form action={deleteShippingMethod.bind(null, m.id)}>
                          <button type="submit" className="text-xs text-stone-400 hover:text-red-700">
                            Delete
                          </button>
                        </form>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
