"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

export default function TicketTypeForm({ eventId }: { eventId: string }) {
  const router = useRouter();
  const [name, setName] = useState("");
  const [price, setPrice] = useState("");
  const [quantity, setQuantity] = useState("");
  const [admits, setAdmits] = useState("1");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setError(null);

    const res = await fetch(`/api/dashboard/events/${eventId}/ticket-types`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        name,
        priceCents: Math.round(parseFloat(price) * 100),
        quantityTotal: parseInt(quantity, 10),
        admitsCount: parseInt(admits, 10) || 1,
      }),
    });

    if (!res.ok) {
      const data = await res.json();
      setError(data.error ?? "Could not add ticket type");
      setLoading(false);
      return;
    }

    setName("");
    setPrice("");
    setQuantity("");
    setAdmits("1");
    setLoading(false);
    router.refresh();
  }

  return (
    <form onSubmit={handleSubmit} className="flex gap-2 items-end flex-wrap">
      <div>
        <label className="block text-xs font-medium mb-1">Name</label>
        <input
          required
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="General Admission"
          className="input w-48"
        />
      </div>
      <div>
        <label className="block text-xs font-medium mb-1">
          {parseInt(admits, 10) > 1 ? "Group price (KES)" : "Price (KES)"}
        </label>
        <input
          required
          type="number"
          min="0"
          step="0.01"
          value={price}
          onChange={(e) => setPrice(e.target.value)}
          className="input w-28"
        />
      </div>
      <div>
        <label className="block text-xs font-medium mb-1">
          {parseInt(admits, 10) > 1 ? "Groups available" : "Quantity"}
        </label>
        <input
          required
          type="number"
          min="1"
          value={quantity}
          onChange={(e) => setQuantity(e.target.value)}
          className="input w-24"
        />
      </div>
      <div>
        <label className="block text-xs font-medium mb-1" title="1 = a normal ticket. More than 1 makes this a group bundle: one purchase issues a separate QR ticket for each person.">
          People per ticket
        </label>
        <input
          required
          type="number"
          min="1"
          max="50"
          value={admits}
          onChange={(e) => setAdmits(e.target.value)}
          className="input w-24"
        />
      </div>
      <button
        type="submit"
        disabled={loading}
        className="rounded-md bg-brand-green text-white px-3 py-2 text-sm font-medium hover:bg-brand-green-deep disabled:opacity-50"
      >
        Add
      </button>
      {parseInt(admits, 10) > 1 && (
        <p className="text-xs text-be-muted w-full">
          Group bundle: each purchase issues {parseInt(admits, 10)} separate QR tickets. Tip: name it e.g. &ldquo;Group of {parseInt(admits, 10)}&rdquo;.
        </p>
      )}
      {error && <p className="text-sm text-red-600 w-full">{error}</p>}
    </form>
  );
}
