"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { buttonClass } from "@/components/ui";
import type { CouponKind } from "@/lib/types";

export default function NewCouponForm({ events }: { events: { id: string; title: string }[] }) {
  const router = useRouter();
  const [form, setForm] = useState({
    code: "",
    eventId: "",
    appliesTo: "tickets" as "tickets" | "merch" | "both",
    kind: "percent" as CouponKind,
    value: "",
    maxRedemptions: "",
    perCustomerLimit: "1",
    startsAt: "",
    endsAt: "",
  });
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setError(null);

    const value = Number(form.value);
    if (!value || value <= 0) {
      setError("Enter a discount value greater than 0");
      setLoading(false);
      return;
    }
    if (form.kind === "percent" && value > 100) {
      setError("A percentage discount can't exceed 100");
      setLoading(false);
      return;
    }

    const res = await fetch("/api/dashboard/coupons", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        eventId: form.eventId || null,
        appliesTo: form.appliesTo,
        code: form.code.trim().toUpperCase(),
        kind: form.kind,
        percentOff: form.kind === "percent" ? value : null,
        amountOffCents: form.kind === "fixed" ? Math.round(value * 100) : null,
        maxRedemptions: form.maxRedemptions ? Number(form.maxRedemptions) : null,
        perCustomerLimit: form.perCustomerLimit ? Number(form.perCustomerLimit) : null,
        startsAt: form.startsAt || null,
        endsAt: form.endsAt || null,
      }),
    });

    if (!res.ok) {
      const data = await res.json();
      setError(data.error ?? "Could not create coupon");
      setLoading(false);
      return;
    }

    router.push("/dashboard/coupons");
    router.refresh();
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <Field label="Code">
        <input
          required
          value={form.code}
          onChange={(e) => setForm({ ...form, code: e.target.value })}
          placeholder="e.g. EARLYBIRD"
          className="input font-mono uppercase"
        />
      </Field>

      <Field label="Discounts">
        <select
          value={form.appliesTo}
          onChange={(e) => setForm({ ...form, appliesTo: e.target.value as typeof form.appliesTo })}
          className="input"
        >
          <option value="tickets">Tickets only</option>
          <option value="merch">Merchandise only</option>
          <option value="both">Tickets and merchandise</option>
        </select>
      </Field>

      <Field label="Applies to">
        <select
          value={form.eventId}
          onChange={(e) => setForm({ ...form, eventId: e.target.value })}
          className="input"
        >
          <option value="">All of your events</option>
          {events.map((ev) => (
            <option key={ev.id} value={ev.id}>
              {ev.title}
            </option>
          ))}
        </select>
      </Field>

      <div className="grid grid-cols-2 gap-3">
        <Field label="Discount type">
          <select
            value={form.kind}
            onChange={(e) => setForm({ ...form, kind: e.target.value as CouponKind })}
            className="input"
          >
            <option value="percent">Percent off</option>
            <option value="fixed">Fixed amount off (KES)</option>
          </select>
        </Field>
        <Field label={form.kind === "percent" ? "Percent" : "Amount (KES)"}>
          <input
            required
            type="number"
            min="1"
            step={form.kind === "percent" ? "1" : "0.01"}
            value={form.value}
            onChange={(e) => setForm({ ...form, value: e.target.value })}
            className="input"
          />
        </Field>
      </div>

      <div className="grid grid-cols-2 gap-3">
        <Field label="Max redemptions" hint="Blank = unlimited">
          <input
            type="number"
            min="1"
            value={form.maxRedemptions}
            onChange={(e) => setForm({ ...form, maxRedemptions: e.target.value })}
            className="input"
          />
        </Field>
        <Field label="Per-customer limit" hint="Blank = unlimited">
          <input
            type="number"
            min="1"
            value={form.perCustomerLimit}
            onChange={(e) => setForm({ ...form, perCustomerLimit: e.target.value })}
            className="input"
          />
        </Field>
      </div>

      <div className="grid grid-cols-2 gap-3">
        <Field label="Starts" hint="Optional">
          <input
            type="datetime-local"
            value={form.startsAt}
            onChange={(e) => setForm({ ...form, startsAt: e.target.value })}
            className="input"
          />
        </Field>
        <Field label="Ends" hint="Optional">
          <input
            type="datetime-local"
            value={form.endsAt}
            onChange={(e) => setForm({ ...form, endsAt: e.target.value })}
            className="input"
          />
        </Field>
      </div>

      {error && <p className="text-sm text-red-600">{error}</p>}

      <button type="submit" disabled={loading} className={buttonClass("primary")}>
        {loading ? "Creating…" : "Create coupon"}
      </button>
    </form>
  );
}

function Field({
  label,
  hint,
  children,
}: {
  label: string;
  hint?: string;
  children: React.ReactNode;
}) {
  return (
    <div>
      <label className="block text-sm font-medium mb-1 text-be-text">
        {label} {hint && <span className="font-normal text-be-muted">— {hint}</span>}
      </label>
      {children}
    </div>
  );
}
