import { prisma } from "@/lib/prisma";
import { formatPaise } from "@/lib/format";
import { getShippingSettings, calculateShippingFee } from "@/lib/shipping";
import { updateShippingMethodRate, updateDeliveryChargeMechanics } from "@/lib/actions/shipping";
import ShippingTabs from "@/components/admin/ShippingTabs";
import SaveIconButton from "@/components/admin/SaveIconButton";

const SAMPLE_WEIGHTS_KG = [0.5, 1, 2, 5, 10];

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

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Delivery Charges</h1>
      <p className="mt-1 text-sm text-stone-500">
        Per-kg rate for each method, plus the rounding rules used to turn a cart&apos;s weight into a billable charge.
      </p>

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

      {error && <p className="mb-4 mt-4 rounded-md bg-red-50 px-3 py-2 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      <div className="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 on the Shipping Methods tab first.
          </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">Method</th>
                <th className="p-3">Rate per kg</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} {m.isDefault && <span className="ml-1 text-xs font-normal text-rose-600">(default)</span>}
                  </td>
                  <td className="p-3">
                    <form action={updateShippingMethodRate.bind(null, m.id)} className="flex items-center gap-1.5">
                      <span className="text-stone-500">₹</span>
                      <input
                        type="number"
                        name="ratePerKg"
                        min={0}
                        step="0.01"
                        defaultValue={m.ratePerKgPaise / 100}
                        className="w-24 rounded border border-stone-300 px-2 py-1 text-sm"
                      />
                      <span className="text-stone-500">/kg</span>
                      <SaveIconButton />
                    </form>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <h2 className="mt-8 text-sm font-semibold text-stone-700">Rounding rules</h2>
      <form action={updateDeliveryChargeMechanics} className="mt-3 grid max-w-2xl grid-cols-1 gap-4 rounded-lg border border-rose-100 bg-white p-4 sm:grid-cols-3">
        <label className="text-xs text-stone-500">
          Weight slab (g)
          <input
            type="number"
            name="weightSlabGrams"
            min={1}
            defaultValue={settings.weightSlabGrams}
            className="mt-1 block w-full rounded-md border border-stone-300 px-2 py-2 text-sm"
          />
          <span className="mt-1 block text-[11px] text-stone-400">Couriers bill in slabs, not exact grams.</span>
        </label>
        <label className="text-xs text-stone-500">
          Minimum billable weight (g)
          <input
            type="number"
            name="minBillableWeightGrams"
            min={0}
            defaultValue={settings.minBillableWeightGrams}
            className="mt-1 block w-full rounded-md border border-stone-300 px-2 py-2 text-sm"
          />
        </label>
        <label className="text-xs text-stone-500">
          Default item weight (g)
          <input
            type="number"
            name="defaultItemWeightGrams"
            min={1}
            defaultValue={settings.defaultItemWeightGrams}
            className="mt-1 block w-full rounded-md border border-stone-300 px-2 py-2 text-sm"
          />
          <span className="mt-1 block text-[11px] text-stone-400">Fallback for products with no weight set.</span>
        </label>
        <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-3">
          Save
        </button>
      </form>

      <h2 className="mt-8 text-sm font-semibold text-stone-700">Preview (below the free-shipping threshold, using the default method)</h2>
      <div className="mt-3 overflow-hidden rounded-lg border border-rose-100 bg-white">
        <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">Cart weight</th>
              <th className="p-3">Billed as</th>
              <th className="p-3">Shipping fee</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-rose-100">
            {SAMPLE_WEIGHTS_KG.map((kg) => {
              const grams = kg * 1000;
              const billableGrams = Math.max(settings.minBillableWeightGrams, Math.ceil(grams / settings.weightSlabGrams) * settings.weightSlabGrams);
              const fee = calculateShippingFee(0, grams, settings);
              return (
                <tr key={kg}>
                  <td className="p-3 text-stone-600">{kg}kg</td>
                  <td className="p-3 text-stone-600">{(billableGrams / 1000).toFixed(2)}kg</td>
                  <td className="p-3 font-medium text-stone-800">{formatPaise(fee)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
