"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { buttonClass } from "@/components/ui";

export default function NewAffiliateForm() {
  const router = useRouter();
  const [form, setForm] = useState({ code: "", name: "", commissionPercent: "10" });
  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 commissionPercent = Number(form.commissionPercent);
    if (!commissionPercent || commissionPercent <= 0 || commissionPercent > 100) {
      setError("Enter a commission between 1 and 100");
      setLoading(false);
      return;
    }

    const res = await fetch("/api/dashboard/affiliates", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        code: form.code.trim().toUpperCase(),
        name: form.name.trim() || null,
        commissionPercent,
      }),
    });

    if (!res.ok) {
      const data = await res.json();
      setError(data.error ?? "Could not create affiliate");
      setLoading(false);
      return;
    }

    router.push("/dashboard/affiliates");
    router.refresh();
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <Field label="Code" hint="Goes in their link, e.g. …/go/your-event/valerian. Letters, numbers, - and _ only.">
        <input
          required
          maxLength={40}
          pattern="[A-Za-z0-9_\-]+"
          title="Letters, numbers, - and _ only (no spaces)"
          value={form.code}
          onChange={(e) => setForm({ ...form, code: e.target.value.replace(/\s+/g, "") })}
          placeholder="e.g. VALERIAN"
          className="input font-mono uppercase"
        />
      </Field>

      <Field label="Promoter name" hint="Optional">
        <input
          value={form.name}
          onChange={(e) => setForm({ ...form, name: e.target.value })}
          placeholder="e.g. John Doe"
          className="input"
        />
      </Field>

      <Field label="Commission (%)" hint="Share of the order total credited on each attributed sale">
        <input
          required
          type="number"
          min="1"
          max="100"
          value={form.commissionPercent}
          onChange={(e) => setForm({ ...form, commissionPercent: e.target.value })}
          className="input"
        />
      </Field>

      {error && <p className="text-sm text-red-600">{error}</p>}

      <button type="submit" disabled={loading} className={buttonClass("primary")}>
        {loading ? "Creating…" : "Create affiliate"}
      </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>
  );
}
