"use client";

import { useActionState } from "react";
import { useFormStatus } from "react-dom";
import Link from "next/link";
import { Loader2 } from "lucide-react";
import { saveCouponAction } from "@/app/actions/admin-coupons";
import type { AdminFormState } from "@/app/actions/admin-products";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";

export type CouponFormValues = {
  id?: string;
  code: string;
  type: string;
  value: string;
  minOrder: string;
  maxUses: string;
  startsAt: string;
  expiresAt: string;
  isActive: boolean;
};

const initial: AdminFormState = { status: "idle" };

function Submit() {
  const { pending } = useFormStatus();
  return (
    <Button type="submit" disabled={pending} className="w-full">
      {pending ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
      {pending ? "Enregistrement…" : "Enregistrer le code"}
    </Button>
  );
}

export function CouponForm({ initialValues }: { initialValues: CouponFormValues }) {
  const [state, action] = useActionState(saveCouponAction, initial);
  const isEdit = Boolean(initialValues.id);

  return (
    <form action={action} className="grid gap-4 xl:grid-cols-[1fr_300px]">
      <input type="hidden" name="id" value={initialValues.id ?? ""} />

      <div className="space-y-4">
        {state.status === "error" && state.message && (
          <p className="border border-terracotta/25 bg-terracotta/5 px-4 py-3 text-[14px] text-terracotta">
            {state.message}
          </p>
        )}

        <section className="border border-line bg-cream p-5">
          <h2 className="font-serif text-xl font-light">Code et remise</h2>
          <div className="mt-4 grid gap-4 sm:grid-cols-2">
            <div>
              <Label htmlFor="code" className="field-label">Code *</Label>
              <Input id="code" name="code" defaultValue={initialValues.code} placeholder="BIENVENUE10" className="h-10 rounded-none font-mono text-[14px] uppercase" />
            </div>
            <div>
              <Label htmlFor="type" className="field-label">Type de remise *</Label>
              <select id="type" name="type" defaultValue={initialValues.type} className="h-10 w-full border border-line bg-transparent px-2.5 text-[14px] focus:border-charcoal focus:outline-none">
                <option value="PERCENT">Pourcentage (%)</option>
                <option value="FIXED">Montant fixe (DH)</option>
              </select>
            </div>
            <div>
              <Label htmlFor="value" className="field-label">Valeur *</Label>
              <Input id="value" name="value" defaultValue={initialValues.value} inputMode="decimal" className="h-10 rounded-none tabular-nums" />
            </div>
            <div>
              <Label htmlFor="minOrder" className="field-label">Commande minimum (DH)</Label>
              <Input id="minOrder" name="minOrder" defaultValue={initialValues.minOrder} inputMode="decimal" className="h-10 rounded-none tabular-nums" />
            </div>
            <div>
              <Label htmlFor="maxUses" className="field-label">Utilisations maximum</Label>
              <Input id="maxUses" name="maxUses" defaultValue={initialValues.maxUses} inputMode="numeric" placeholder="Illimité" className="h-10 rounded-none tabular-nums" />
            </div>
            <label className="flex items-end gap-2.5 pb-2.5 text-[14px] text-walnut">
              <input type="checkbox" name="isActive" defaultChecked={initialValues.isActive} className="h-3.5 w-3.5 accent-charcoal" />
              Code actif
            </label>
          </div>
        </section>

        <section className="border border-line bg-cream p-5">
          <h2 className="font-serif text-xl font-light">Validité</h2>
          <p className="mt-1 text-[13px] text-pebble">Laissez vide pour un code sans date de début ou de fin.</p>
          <div className="mt-4 grid gap-4 sm:grid-cols-2">
            <div>
              <Label htmlFor="startsAt" className="field-label">Début</Label>
              <Input id="startsAt" name="startsAt" type="date" defaultValue={initialValues.startsAt} className="h-10 rounded-none text-[14px]" />
            </div>
            <div>
              <Label htmlFor="expiresAt" className="field-label">Fin</Label>
              <Input id="expiresAt" name="expiresAt" type="date" defaultValue={initialValues.expiresAt} className="h-10 rounded-none text-[14px]" />
            </div>
          </div>
        </section>
      </div>

      <aside>
        <div className="border border-line bg-cream p-4">
          <Submit />
          <Link href="/admin/coupons" className="mt-2 block text-center text-[12px] uppercase tracking-[0.12em] text-pebble hover:text-charcoal">
            Annuler
          </Link>
          {isEdit && (
            <p className="mt-4 border-t border-line pt-3 text-[12px] leading-relaxed text-pebble">
              Le compteur d'utilisations n'est pas modifiable manuellement.
            </p>
          )}
        </div>
      </aside>
    </form>
  );
}
