"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

export default function CompTicketForm({
  eventId,
  ticketTypes,
}: {
  eventId: string;
  ticketTypes: { id: string; name: string }[];
}) {
  const router = useRouter();
  const [ticketTypeId, setTicketTypeId] = useState(ticketTypes[0]?.id ?? "");
  const [quantity, setQuantity] = useState("1");
  const [recipientName, setRecipientName] = useState("");
  const [recipientEmail, setRecipientEmail] = useState("");
  const [recipientPhone, setRecipientPhone] = useState("");
  const [reason, setReason] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setSuccess(null);

    const res = await fetch(`/api/dashboard/events/${eventId}/comp-tickets`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        ticketTypeId,
        quantity: parseInt(quantity, 10),
        recipientName,
        recipientEmail,
        recipientPhone: recipientPhone || undefined,
        reason: reason || undefined,
      }),
    });

    if (!res.ok) {
      const data = await res.json();
      setError(data.error ?? "Could not issue complimentary ticket");
      setLoading(false);
      return;
    }

    setSuccess(`Sent to ${recipientEmail}.`);
    setRecipientName("");
    setRecipientEmail("");
    setRecipientPhone("");
    setReason("");
    setQuantity("1");
    setLoading(false);
    router.refresh();
  }

  if (!ticketTypes.length) {
    return <p className="text-sm text-be-muted">Add a ticket type first to issue complimentary tickets.</p>;
  }

  return (
    <form onSubmit={handleSubmit} className="flex gap-2 items-end flex-wrap">
      <div>
        <label className="block text-xs font-medium mb-1">Ticket type</label>
        <select
          required
          value={ticketTypeId}
          onChange={(e) => setTicketTypeId(e.target.value)}
          className="input w-40"
        >
          {ticketTypes.map((tt) => (
            <option key={tt.id} value={tt.id}>
              {tt.name}
            </option>
          ))}
        </select>
      </div>
      <div>
        <label className="block text-xs font-medium mb-1">Quantity</label>
        <input
          required
          type="number"
          min="1"
          max="50"
          value={quantity}
          onChange={(e) => setQuantity(e.target.value)}
          className="input w-20"
        />
      </div>
      <div>
        <label className="block text-xs font-medium mb-1">Recipient name</label>
        <input
          required
          value={recipientName}
          onChange={(e) => setRecipientName(e.target.value)}
          placeholder="Jane Doe"
          className="input w-40"
        />
      </div>
      <div>
        <label className="block text-xs font-medium mb-1">Recipient email</label>
        <input
          required
          type="email"
          value={recipientEmail}
          onChange={(e) => setRecipientEmail(e.target.value)}
          placeholder="jane@example.com"
          className="input w-52"
        />
      </div>
      <div>
        <label className="block text-xs font-medium mb-1">Phone (optional)</label>
        <input
          value={recipientPhone}
          onChange={(e) => setRecipientPhone(e.target.value)}
          placeholder="07..."
          className="input w-32"
        />
      </div>
      <div>
        <label className="block text-xs font-medium mb-1">Reason (optional)</label>
        <input
          value={reason}
          onChange={(e) => setReason(e.target.value)}
          placeholder="Media, sponsor, guest..."
          className="input w-40"
        />
      </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"
      >
        {loading ? "Sending…" : "Issue free ticket"}
      </button>
      {error && <p className="text-sm text-red-600 w-full">{error}</p>}
      {success && <p className="text-sm text-brand-green w-full">{success}</p>}
    </form>
  );
}
