import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { BackLink } from "@/components/back-link";
import { updateDiscountCodeAction } from "../../actions";
import { getLocale } from "@/i18n/locale";
import { getDictionary } from "@/i18n/get-dictionary";

function toDateInputValue(date: Date | null): string {
  if (!date) return "";
  return date.toISOString().slice(0, 10);
}

export default async function AdminGutscheinEditPage(props: PageProps<"/admin/gutscheine/[id]">) {
  const t = getDictionary(await getLocale());
  const { id } = await props.params;
  const { error } = await props.searchParams;
  const code = await prisma.discountCode.findUnique({ where: { id } });
  if (!code) notFound();

  return (
    <div className="max-w-md">
      <BackLink href="/admin/gutscheine" label={t.adminVoucherEditPage.backToVouchers} />
      <h1 className="text-2xl text-forest mb-8">{t.adminVoucherEditPage.title}</h1>

      {error ? (
        <p className="mb-6 text-sm text-red-700 bg-red-50 border border-red-200 px-4 py-3">{error}</p>
      ) : null}

      <form action={updateDiscountCodeAction} className="space-y-4 bg-background border border-ink/10 p-6">
        <input type="hidden" name="id" value={code.id} />
        <Field name="code" label={t.adminVoucherEditPage.codeLabel} defaultValue={code.code} required />

        <div className="grid grid-cols-2 gap-4">
          <label className="block text-sm">
            <span className="text-ink/70">{t.adminVoucherEditPage.typeLabel}</span>
            <select
              name="type"
              defaultValue={code.type}
              className="mt-1 w-full border border-ink/20 bg-background px-3 py-2"
            >
              <option value="PERCENT">{t.adminVoucherEditPage.typePercent}</option>
              <option value="FIXED">{t.adminVoucherEditPage.typeFixed}</option>
            </select>
          </label>
          <Field name="value" label={t.adminVoucherEditPage.valueLabel} type="number" defaultValue={String(code.value)} required />
        </div>

        <Field
          name="minOrderCents"
          label={t.adminVoucherEditPage.minOrderLabel}
          type="number"
          defaultValue={String(code.minOrderCents)}
        />
        <Field
          name="minQuantity"
          label={t.adminVoucherEditPage.minQuantityLabel}
          type="number"
          defaultValue={code.minQuantity !== null ? String(code.minQuantity) : ""}
        />
        <Field
          name="maxUses"
          label={t.adminVoucherEditPage.maxUsesLabel}
          type="number"
          defaultValue={code.maxUses !== null ? String(code.maxUses) : ""}
        />

        <div className="grid grid-cols-2 gap-4">
          <Field
            name="validFrom"
            label={t.adminVoucherEditPage.validFromLabel}
            type="date"
            defaultValue={toDateInputValue(code.validFrom)}
          />
          <Field
            name="validUntil"
            label={t.adminVoucherEditPage.validUntilLabel}
            type="date"
            defaultValue={toDateInputValue(code.validUntil)}
          />
        </div>

        <label className="flex items-center gap-2 text-sm text-ink/70">
          <input type="checkbox" name="isActive" defaultChecked={code.isActive} />
          {t.adminVoucherEditPage.activeLabel}
        </label>

        <p className="text-xs text-ink/65">{t.adminVoucherEditPage.redeemedSoFar(code.usedCount, code.maxUses)}</p>

        <button type="submit" className="bg-forest text-cream px-6 py-2 text-sm">
          {t.adminVoucherEditPage.save}
        </button>
      </form>
    </div>
  );
}

function Field({
  name,
  label,
  type = "text",
  defaultValue,
  required = false,
}: {
  name: string;
  label: string;
  type?: string;
  defaultValue?: string;
  required?: boolean;
}) {
  return (
    <label className="block text-sm">
      <span className="text-ink/70">{label}</span>
      <input
        name={name}
        type={type}
        defaultValue={defaultValue}
        required={required}
        min={0}
        className="mt-1 w-full border border-ink/20 bg-background px-3 py-2"
      />
    </label>
  );
}
