import Link from "next/link";
import { notFound } from "next/navigation";
import { Trash2 } from "lucide-react";
import { prisma } from "@/lib/prisma";
import { AdminPageHeader } from "@/components/admin/page-header";
import { ConfirmButton } from "@/components/admin/confirm-button";
import { CouponForm, type CouponFormValues } from "@/components/admin/coupon-form";
import { deleteCouponAction } from "@/app/actions/admin-coupons";

function toDateInput(date: Date | null): string {
  if (!date) return "";
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

export default async function AdminEditCouponPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const { id } = await params;
  const query = await searchParams;
  const coupon = await prisma.coupon.findUnique({ where: { id } });
  if (!coupon) notFound();

  const values: CouponFormValues = {
    id: coupon.id,
    code: coupon.code,
    type: coupon.type,
    value: coupon.type === "FIXED" ? String(coupon.value / 100) : String(coupon.value),
    minOrder: String(coupon.minOrder / 100),
    maxUses: coupon.maxUses === null ? "" : String(coupon.maxUses),
    startsAt: toDateInput(coupon.startsAt),
    expiresAt: toDateInput(coupon.expiresAt),
    isActive: coupon.isActive,
  };

  return (
    <div className="space-y-5">
      <AdminPageHeader
        eyebrow="Marketing"
        title={coupon.code}
        description={`${coupon.usedCount} utilisation(s) · créé le ${new Intl.DateTimeFormat("fr-FR", { day: "numeric", month: "long", year: "numeric" }).format(coupon.createdAt)}`}
        actions={
          <form action={deleteCouponAction}>
            <input type="hidden" name="id" value={coupon.id} />
            <ConfirmButton
              message="Supprimer ce code promo ? Les commandes passées conservent leur remise."
              className="inline-flex h-9 items-center gap-2 border border-terracotta/25 px-3 text-[12px] uppercase tracking-[0.12em] text-terracotta/70 hover:border-terracotta hover:text-terracotta"
            >
              <Trash2 className="h-3.5 w-3.5" />
              Supprimer
            </ConfirmButton>
          </form>
        }
      />

      {typeof query.saved === "string" && (
        <p className="border border-olive/25 bg-olive/5 px-4 py-3 text-[14px] text-olive">Le code promo a été enregistré.</p>
      )}

      <CouponForm initialValues={values} />

      <p className="text-[12px] text-pebble">
        Voir aussi{" "}
        <Link href="/admin/orders" className="underline underline-offset-4 hover:text-charcoal">les commandes</Link>
        {" "}pour suivre l'usage réel des remises.
      </p>
    </div>
  );
}
